/**
 * 
 */
var authorizeUri = IsAuthorize > 0 ? "&authorize=1&sid="+SID : "",	//授权用户发课
	partOpCode = {'add':1,'edit':2,'del':3},
	sectionOpCode = {'add':1,'edit':2,'del':3},
	studyType = {'curr' : 1, 'video' : 2, 'live' : 3, 'offline' : 4},
	editoffline = 0,
	psstudyType = { 'attach' : 1, 'video' : 2 },
	Coureswares = [];

var delOfflines = [];

$.fn.dance = function(obj) {
	for ( var eName in obj)
		for ( var selector in obj[eName])
			$(this).on(eName, selector, obj[eName][selector]);
}

var getTimeOptions = function(select_val){
	if(Course1V1){
		if(typeof(select_val) == "undefined"){
			var TimeOptionsHtml = [
       			'<option value="60">1小时</option>',
       			'<option value="120">2小时</option>',
       			'<option value="180">3小时</option>',
       			'<option value="240">4小时</option>',
       	    ].join('');
		}else{
			if(IsTeacher){
				var TimeOptionsHtml = [
					'<option value="'+select_val+'" selected="selected">'+parseInt(select_val)/60+'小时</option>'
	    	    ].join('');
			}else{
				var TimeOptionsHtml = [
	   				'<option value="60" '+(select_val==60?'selected="selected"':'')+'>1小时</option>',
	   				'<option value="120" '+(select_val==120?'selected="selected"':'')+'>2小时</option>',
	   				'<option value="180" '+(select_val==180?'selected="selected"':'')+'>3小时</option>',
	   				'<option value="240" '+(select_val==240?'selected="selected"':'')+'>4小时</option>',
         	    ].join('');
			}
		}
	}else{
		if(typeof(select_val) == "undefined"){
			var TimeOptionsHtml = [
				'<option value="15">15分钟</option>',
				'<option value="20">20分钟</option>',
				'<option value="30">30分钟</option>',
				'<option value="45">45分钟</option>',
				'<option value="60">60分钟</option>',
				'<option value="90">90分钟</option>',
				'<option value="120">120分钟</option>',
				'<option value="150">150分钟</option>',
				'<option value="180">3小时</option>',
				'<option value="240">4小时</option>',
				'<option value="360">6小时</option>',
				'<option value="480">8小时</option>',
		    ].join('');
		}else{
			var TimeOptionsHtml = [
				'<option value="15" '+(select_val==15?'selected="selected"':'')+'>15分钟</option>',
				'<option value="20" '+(select_val==20?'selected="selected"':'')+'>20分钟</option>',
				'<option value="30" '+(select_val==30?'selected="selected"':'')+'>30分钟</option>',
				'<option value="45" '+(select_val==45?'selected="selected"':'')+'>45分钟</option>',
				'<option value="60" '+(select_val==60?'selected="selected"':'')+'>60分钟</option>',
				'<option value="90" '+(select_val==90?'selected="selected"':'')+'>90分钟</option>',
				'<option value="120" '+(select_val==120?'selected="selected"':'')+'>120分钟</option>',
				'<option value="150" '+(select_val==150?'selected="selected"':'')+'>150分钟</option>',
				'<option value="180" '+(select_val==180?'selected="selected"':'')+'>3小时</option>',
				'<option value="240" '+(select_val==240?'selected="selected"':'')+'>4小时</option>',
				'<option value="360" '+(select_val==360?'selected="selected"':'')+'>6小时</option>',
				'<option value="480" '+(select_val==480?'selected="selected"':'')+'>8小时</option>',
   		    ].join('');
		}
	}
	return TimeOptionsHtml;
}

var resetSectionNu = function(SectionBox){
	var sections = SectionBox.find("div.item");
	if(sections.length > 0){
		$.each(sections, function(i, n){
			var temp = $(n).find("span.i_num"),
				tempTxt = temp.text();
			temp.text(tempTxt.replace(/\d+/g, i+1));
		});
	}
}

var resetSectionIdx = function($editItem){
	var $partBox = $editItem.parent("div.sedu_tBox"),
		$followSection = $editItem.nextAll("div.itemRow"),
		$followPart = $partBox.nextAll("div.sedu_tBox");
	if($followSection.length > 0){
		$.each($followSection, function(i, n){
			var tmpIdx = parseInt($(n).attr('sectionidx'));
			$(n).attr('sectionidx', tmpIdx+1);
		});
	}
	if($followPart.length > 0){
		for(var i=0; i<$followPart.length; i++){
			var $followPartSection = $($followPart[i]).find('div.itemRow');
			$.each($followPartSection, function(i, n){
				var tmpIdx = parseInt($(n).attr('sectionidx'));
				$(n).attr('sectionidx', tmpIdx+1);
			});
		}
	}
}

var resetPartNu = function(){
	var parts = $("#CourseDanceBox").find("div.sedu_t");
	if(parts.length > 0){
		$.each(parts, function(i, n){
			var temp = $(n).find("h2"),
				tempTxt = temp.text();
			temp.text(tempTxt.replace(/^第 \d+ 章/, "第 "+parseInt(i+1)+" 章"));
		});
	}
}

var filterTitle = function(str){
	return str.replace(/[\\\\\/:\"\'\*\?<>\|]/ig, '');
}

var checkCurrClassEdit = function(CID, OP){
	var ret = true;
	if(Course1V1){
		var CourseType = "&coursetype=2";
	}else{
		var CourseType = "";
	}
	if(IsTeacher > 0){
		var url = "/?mod=course&act=edit&do=check"+CourseType+"&courseid="+CourseID+"&cid="+CID+"&op="+OP+"&isteacher=1&isajax=1&random="+Math.random();
	}else{
		var url = "/?mod=course&act=edit&do=check"+authorizeUri+CourseType+"&cid="+CID+"&op="+OP+"&random="+Math.random();
	}
	if(HasBuyer > 0 || IsTeacher > 0 || Course1V1){
		$.ajax({
			url : url,
			type : "get",
			async : false,
			dataType : "json",
			success : function(rs){
				if(rs.code < 0){
					$.ckAlert({message:rs.data});
					ret = false;
				}
			}
		});
	}
	return ret;
}

var getCurrClassTimeLenth = function(val){
	if(val.match(/^\d+分钟$/)){
		return val.replace(/分钟$/, '');
	}else if(val.match(/^\d{1}小时$/)){
		return parseInt(val.match(/^\d{1}/))*60;
	}else if(val.match(/^\d{1}小时\d+分钟$/)){
		var tmp = val.replace(/^(\d{1})小时(\d+)分钟$/, "$1*60+$2");
		return eval(tmp);
	}
}

var correctQuoteVideoSrc = function(src){
	if(src == ''){
		return src;
	}else if(src.match(/^(http:\/\/|https:\/\/){1}/i)){
		return src;
	}else{
		return "http://"+src;
	}
}

var getMaxSectionIdx = function(){
	var Idx = 1,
		items = $("div.itemRow");
	if(items.length > 0){
		$.each(items, function(i, n){
			var itemIdx = parseInt($(n).attr('sectionidx'));
			if( itemIdx > Idx){
				Idx = itemIdx
			}
		});
		Idx = parseInt(Idx) + 1;
	}
	return Idx;
}

var formatClassTimeLength = function(val) {
	var timeLength = '';
	if (val < 60) {
		timeLength = val + '分钟';
	} else {
		var min = '';
		if (parseInt(val % 60) != 0) {
			min = parseInt(val % 60) + '分钟';
		}
		timeLength = parseInt(val / 60) + '小时' + min;
	}
	return timeLength;
}

var checkClassName = function(className){
	var charLen = getStrActualLen(className);
	if(charLen < 4 || charLen > 60){
		return false;
	}
	return true;
}

var checkBrief = function(brief){
	var charLen = getStrActualLen(brief);
	if(charLen > 1000){
		return false;
	}
	return true;
}

var removeHTMLTag = function(str){
	if(str != ''){
		str = str.replace(/<\/?[^>]*>/g, '');
	    str = str.replace(/[ | ]*\n/g,'\n');
	    str = str.replace(/\n[\s| | ]*\r/g,'\n');
	    str = $.trim(str);
	}
    return str;
}

var autoUnitAdjust = function(UnitInfo) {
	Coureswares    = [];
	Coureswares[1] = [];
	Coureswares[2] = [];
	Coureswares[3] = [];
	var unitNum    = 1;
	for (var i = 1; i < UnitInfo.length; i++) {
		if (UnitInfo[i].length <= 0) {
			continue;
		} else {
			Coureswares[unitNum] = UnitInfo[i];
			unitNum += 1;
		}
	}
}

var addPart = function($obj, op){
	var html = [
        op == partOpCode.edit ? '<div style="display:none" stepidx="'+$obj.attr("stepidx")+'" stepid="'+$obj.attr("stepid")+'" class="sedu_t_edit mt20 edit_part_type">' : '<div style="display:none" class="sedu_t_edit">',
		'<div class="ml10 clearfix pt10">',
		op == partOpCode.edit ? '<input type="text" style="width:390px" class="form_text fl mr25" value="'+$obj.find("h2").text().replace(/^第 \d+ 章：/, "")+'">' : '<input type="text" style="width:390px" class="form_text fl mr25">',
		'<a href="javascript:;" class="n_btn30g fl add_part_submit mr15">保存</a>',
		'<a href="javascript:;" class="n_btn30gr_b add_part_cancel fl">取消</a>',
		'<span class="tips_txt">5-30个字符支持汉字、数字、“_”</span></div></div>'
    ].join("");
	$obj.before(html);
	$obj.prev("div.sedu_t_edit").fadeIn("fast").find("input").focus();
}

var addSection = function($obj, type){
	if(typeof(type) == "undefined"){
		var section_order = parseInt($obj.parent(".sedu_tBox").find("div.item").length+1);
	}else if(type == "insert_before"){
		var section_order = parseInt($obj.find("span.i_num").text().match(/\d+/)),
			section_order = (section_order - 1) <= 0 ? 1 : section_order;
	}else{
		var section_order = parseInt($obj.find("span.i_num").text().match(/\d+/))+1;
	}
	
	var courseware_url = '';
	if(IsAuthorize) {
		courseware_url = '?mod=teacher&amp;act=courseware&amp;do=iupload&amp;authorize='+IsAuthorize+'&amp;sid='+SID;
	} else {
		courseware_url = '?mod=seller&amp;act=courseware&amp;do=iupload';
	}
	
	var html = [
		typeof(type) == "undefined" ? '<div class="item">' : '<div class="item" type="'+type+'" style="display:none">',
		'<span class="i_num">第'+section_order+'节</span>',
		'<div class="i_con">',
		'<div class="pr clearfix mt7">',							
		'<input type="text" class="form_text w500 fl" id="class_name_text">',
		'</div></div></div>',
        '<div class="subBox" style="display:none">',
        '<div class="subBox_c">',
        Individuation == 1 ? '<div class="subPoint"><input type="hidden" name="klid" id="select_kl_id" /><div class="pr clearfix mt7 b"><span class="fl"><span style="line-height: 35px;" id="select_kl_text">知识点为空，请点击关联选择知识点</span></span><span><a href="javascript:void(0);" id="add_knowledge" class="n_btn34lg_add add_knowledge ml5">关联知识点</a></span></div></div>' : '',
		'<div class="pr mb10 clearfix">',
		'<textarea class="textarea500 fl" name="" id="" cols="" rows=""></textarea>',
		'</div>',
		'<div class="mt20">',
		Individuation == 0 ? '<a class="n_btn34lg_add mr15 select_class" type="live_class" href="javascript:;">安排直播课</a>' : '',
		Individuation == 0 ? '<a class="n_btn34lg_add mr15 select_class" type="video_class" href="javascript:;">安排视频课</a>' : '',
		((Individuation == 0 && Offline == 1) || (IsAuthorize == 1 && Offline == 1)) ? '<a class="n_btn34lg_add mr15 select_class" type="offline_class" href="javascript:;">安排线下课</a>' : '',
//		Individuation == 1 ? '<a class="n_btn34lg_add mr15 select_couresware_class" type="video_class" href="javascript:;">安排视频课</a>' : '',
//		Individuation == 1 ? '<a class="n_btn34lg_add mr15 select_couresware_class" type="courseware_class" href="javascript:;">添加课件</a>' : '',
		Individuation == 1 ? '<div class="mb20"><a class="ps_unit_box_add n_btn34lg_add ml20" href="javascript:;"><span>添加新的学习单元</span></a></div>' : '',
		Individuation == 1 ? '<div id="ps_unit_box"></div>' : '',
//		Individuation == 1 ? '<div style="" id="ps_courseware_box" class="s_videoCon attach_class_box"><div class="s_inner"><div class="s_i_hd"><a href="javascript:;" class="n_btn34lg_add mr15 pickCoureswares"><span>从课件库中选择</span></a><span class="s_i_hd_tips">未上传的课件请先上传至课件库 <a target="_blank" href="'+courseware_url+'" class="c_0065cb">上传课件</a></span></div><div id="selectedCourseware" class="s_i_hd"></div></div></div>' : '',
		IsQuote == true ? '<a class="n_btn34lg_add mr15 select_class" type="outsite_link" href="javascript:;">引用站外视频</a>' : '',
		'</div><div class="mb10 mt15">',
        Course1V1 == false && Individuation == 0 ? '<label><input type="checkbox" class="mr5 free_trial">本节允许免费试听，学生无需购买就可以免费学习整节课程。</label>' : '',
		'</div><div class="mt20 mb25">',
		Individuation == 0 ? '<a class="n_btn34g mr20 submit_section" href="javascript:;">保存</a>' : '',
		Individuation == 1 ? '<a class="n_btn34g mr20 submit_is_section" href="javascript:;">保存</a>' : '',
		'<a class="n_btn34gr_b" href="javascript:;">取消</a>',
		'</div></div></div>'
	].join("");
	
	if(typeof(type) == "undefined"){
		$obj.before(html);
		$obj.prev("div.subBox").slideDown("fast");
	}else if(type == "insert_before"){
		$obj.before(html);
		$obj.prev().prev("div.item").slideDown("fast", function(){
			$obj.prev("div.subBox").slideDown("fast");
			resetSectionNu($obj.parent("div.sedu_tBox"));
		});
	}else{
		$obj.next("div.subBox").after(html);
		$obj.next().next("div.item").slideDown("fast", function(){
			$(this).next("div.subBox").slideDown("fast");
			resetSectionNu($obj.parent("div.sedu_tBox"));
		});
	}
}

var moveSection = function($base_item, $to_item, type){
	var cid			= $base_item.attr("cid"),
	 	section_idx = type == "up" ? $to_item.attr("sectionidx") : parseInt($to_item.attr("sectionidx")) + 1,
		$base_subox = $("#section_"+cid),
		tipsBox = null;
		
	if(IsTeacher){
		var url = "/?mod=course&act=create&do=sectionChgIdx&isteacher=1&random="+Math.random();
	}else{
		var url = "/?mod=course&act=create&do=sectionChgIdx"+authorizeUri+"&random="+Math.random();
	}
	$.ajax({
		url : url,
		type : "post",
		dataType : "json",
		async : true,
		data : "cid="+cid+"&class_index="+section_idx+"&courseid="+CourseID+"&sid="+SID,
		beforeSend : function(){
			tipsBox = $.ckTipsBoxy({
				message : "移动中...",
				mask : true,
				type : "loading"
			});
		},
		success : function(rs){
			if(rs.code > 0){
				$base_item.removeClass('item_hover');
				tipsBox.cancel();
				$base_item.attr("sectionidx", section_idx);
				if(type == "up"){
					$to_item.before($base_item).before($base_subox);
				}else{
					$to_item.next("div.subBox").after($base_subox).after($base_item);
				}
				resetSectionNu($base_item.parent("div.sedu_tBox"));
				resetSectionIdx($base_item);
			}else{
				$.ckTipsBoxy({
					message : rs.data,
					type : "error"
				});
			}
		}
	});
}

var editSection = function(class_info) {
	if (class_info.study_type == studyType.curr || class_info.study_type == studyType.live) {
		var prelect_start_time = class_info.prelect_start_time.toString().split(" "),
			class_box = [
	            '<div class="s_videoCon live_class_box">',
	            '<div class="s_inner pb10">',
	            '<div class="s_i_hd"><div class="s_i_hd_notice">',
	            Course1V1 == true ? '' : '<div class="fl"><img src="http://res.ckimg.com/sites/www/v2/images/public/ico_warning_16x16.png" alt=""></div>',
	            Course1V1 == true ? '' : '<div class="fl">',
	            Course1V1 == true ? '' : '<p><span>你设定的限购人数大于直播教室的容量，当购买人数超过教室容量时，存在某些用户无法进入教室的风险。</span></p>',
	            Course1V1 == true ? '' : '<p><a href="http://www.chuanke.com/?mod=help&act=index&do=showInfo&SID=211&HID=20&PID=345" target="_blank">了解详情&gt;&gt;</a></p></div>',
	            '</div></div><div class="s_i_bd"><form action="" class="s_i_form clearfix">',
	            (Live == 1 || (IsAuthorize == 1 && Live == 1)) ? '<div class="formItem">' : '',
    			(Live == 1 || (IsAuthorize == 1 && Live == 1)) ? '<label class="form_label" for="">' : '',
    			(Live == 1 || (IsAuthorize == 1 && Live == 1)) ? '<i>*</i><span>直播模式：</span></label>' : '',
    			(Live == 1 || (IsAuthorize == 1 && Live == 1)) ? '<div class="form_field">' : '',
    			(Live == 1 || (IsAuthorize == 1 && Live == 1)) ? '<label class="mr20">' : '',
    			(Live == 1 || (IsAuthorize == 1 && Live == 1)) && (class_info.study_type == 1) ? '<input type="radio" name="live_model" value="1" checked="checked" />' : (Live == 1 || (IsAuthorize == 1 && Live == 1)) ? '<input type="radio" name="live_model" value="1" />' : '',
    			(Live == 1 || (IsAuthorize == 1 && Live == 1)) ? '<span class="f12">实时直播</span></label><label>' : '',
    			(Live == 1 || (IsAuthorize == 1 && Live == 1)) && (class_info.study_type == 3) ? '<input type="radio" name="live_model" value="3" checked="checked" />' : (Live == 1 || (IsAuthorize == 1 && Live == 1)) ? '<input type="radio" name="live_model" value="3" />' : '',
    			(Live == 1 || (IsAuthorize == 1 && Live == 1)) ? '<span class="f12"> Live直播</span></label>' : '',
    		    (Live == 1 || (IsAuthorize == 1 && Live == 1)) ? '<span class="pr"> <a id="liveZBiHelp" href="javascript:;" class="liveZBiHelp i_help"> </a>' : '',
    		    (Live == 1 || (IsAuthorize == 1 && Live == 1)) ?	'<div class="p-live-tips-wrap" style="display: none;"><dl class="p-live-tips"><dt><span class="fn">live直播：</span></dt><dd>一种适合于大量学员的直播方式，但相比实时直播，时间略有延迟。</dd><dd><i class="arrow-down"></i></dd></dl></div></span>' : '',
    		    (Live == 1 || (IsAuthorize == 1 && Live == 1)) ?	'</div></div>' : '',
	            '<div class="formItem">',
	            '<label for="" class="form_label"><i>*</i><span>直播时间：</span></label><div class="form_field">',
	            IsTeacher > 0 ? '<input type="text" disabled="disabled" class="form_text form_text_s_i ymd" value="'+prelect_start_time[0]+'"> ' : '<input type="text" class="form_text form_text_s_i ymd" value="'+prelect_start_time[0]+'" onClick="WdatePicker({dateFmt:\'yyyy年MM月dd日\',minDate:\'%y-%M-%d\', maxDate:\''+ExpiryTime+'\'})"> ',
	            IsTeacher > 0 ? '<input type="text" disabled="disabled" class="form_text form_text_s_i hi" value="'+prelect_start_time[1]+'">' : '<input type="text" class="form_text form_text_s_i hi" onclick="timepicker(this)" value="'+prelect_start_time[1]+'">',
	            '</div><div style="text-indent:7em;" class="c_999">请谨慎设置直播课时间，以防学生在学习有效期内无法上直播课带来纠纷。</div></div><div class="formItem"><label for="" class="form_label"><i>*</i><span>课程时长：</span></label>',
	            '<div class="form_field"><select name="prelect_time_length" class="selt-kcsc">'+getTimeOptions(class_info.prelect_time_length)+'</select>',
	            '</div></div><div class="formItem"><label for="" class="form_label"><i>*</i><span>选择老师：</span></label>',
	            '<div class="form_field"><img width="60" class="s_i_picTeacher" src="'+class_info.teacher_pic+'" uid="'+class_info.teacher_uid+'" title="'+class_info.teacher_name+'" height="60"> ',
	            IsTeacher > 0 ? '' : '<a href="javascript:;" class="n_btn30gr_b pickTeacher">更换老师</a>',
	            '</div></div></form></div></div></div>'
	        ].join("");
	} else if(class_info.study_type == studyType.offline) {
		var prelect_start_time = class_info.prelect_start_time.toString().split(" "),
		    prelect_end_time   = class_info.prelect_end_time.toString().split(" "),
		    class_box = [
	            '<div class="s_videoCon offline_class_box">',
	            '<div class="s_inner">',
		            '<div class="form-wrap-xx clearfix">',
			            '<div class="formItem clearfix mb20" style="border-bottom:1px solid #dbdbdb;">',
			                '<div class="form_label">上课时间：</div>',
			                '<div class="form_field">',
			                    '<span class="pr mr15 ip-r">',
			                        '<input type="text" onClick="WdatePicker({dateFmt:\'yyyy年MM月dd日\',minDate:\'%y-%M-%d\', maxDate:\''+ExpiryTime+'\'})" value="'+prelect_start_time[0]+'" class="form_text date" id="offline_start_date">',
			                        '<span class="iptTips"></span>',
			                    '</span>',
			                    '<span class="pr mr15 ip-r">',
			                        '<input type="text" onClick="timepicker(this)" value="'+prelect_start_time[1]+'" class="form_text date" id="offline_start_time">',
			                        '<span class="iptTips"></span>',
			                    '</span>',
			                    '<span class="mr15">至</span>',
			                    '<span class="pr mr15 ip-r">',
			                        '<input type="text" onClick="WdatePicker({dateFmt:\'yyyy年MM月dd日\',minDate:\'%y-%M-%d\', maxDate:\''+ExpiryTime+'\'})" value="'+prelect_end_time[0]+'" class="form_text date" id="offline_end_date">',
			                        '<span class="iptTips"></span>',
			                    '</span>',
			                    '<span class="pr mr15 ip-r">',
			                        '<input type="text" onClick="timepicker(this)" value="'+prelect_end_time[1]+'"class="form_text date"  id="offline_end_time">',
			                        '<span class="iptTips"></span>',
			                    '</span>',
			                '</div>',
			                '<div style="text-indent:5em;" class="c_999">&nbsp;&nbsp;请谨慎设置线下课时间，以防学生在学习有效期内无法上线下课带来纠纷。</div>',
			            '</div>',
			            '<div class="formItem clearfix">',
			                '<div class="form_label">上课地点：</div>',
			                '<div class="form_field">',
				                '<ul class="addr-list"></ul>',
			                	'<div class="add-box" style="display:none;">',
				                	'<div class="mb15">',
			                            '<select name="" id="idProvince">',
			                                '<option value="">省/直辖市</option>',
			                            '</select>',
			                            '<select name="" id="idCity">',
			                                '<option value="">市区</option>',
			                            '</select>',
			                        '</div>',
			                        '<div class="mb15">',
			                            '<span class="pr ip-r">',
			                                '<input type="text" class="form_text offline_address" style="width: 514px;">',
			                                '<span class="iptTips offline_address_tips">详细地址</span>',
			                            '</span>',
			                        '</div>',
			                        '<div>',
		                            	'<a href="javascript:;" class="n_btn34lg mr20 offline_address_submit">保存</a>',
		                            	'<a href="javascript:;" class="n_btn34lg offline_address_cancel">取消</a>',
		                            '</div>',
			                	'</div>',
			                    '<div>',
			                        '<a href="javascript:;" class="add-link add_offline_box"><i></i>新增上课地点</a>',
			                    '</div>',
			                '</div>',
			            '</div>',
			        '</div>',
			    '</div>',
	            '</div>'
			].join("");
    } else {
    	//个性化学习模块
    	if (Individuation == 1) {
    		var attach_list_html = '',
    		    attach_list_head = '<div class="cell-item-wrap mb20">',
    			attach_list_desc = '<div class="c_999 mb20">你可以通过拖拽改变个性化学习先后顺序。</div>';
    		
    			if (class_info.attachs[1] != '') {
    				attach_list_html += attach_list_head;
    				attach_list_html += '<div class="mb10">学习单元1</div>';
    				attach_list_html += buildCoursewareListNode(1, class_info.attachs);
    				attach_list_html += attach_list_desc + '</div>';
    			}
    			if (class_info.attachs[2] != '') {
    				attach_list_html += attach_list_head;
    				attach_list_html += '<div class="mb10">学习单元2</div>';
    				attach_list_html += buildCoursewareListNode(2, class_info.attachs);
    				attach_list_html += attach_list_desc + '</div>';
    			}
    			if (class_info.attachs[3] != '') {
    				attach_list_html += attach_list_head;
    				attach_list_html += '<div class="mb10">学习单元3</div>';
    				attach_list_html += buildCoursewareListNode(3, class_info.attachs);
    				attach_list_html += attach_list_desc + '</div>';
    			}
			var class_box = [
			        '<div class="mt20">',
			        '<div class="mb20"><a href="javascript:;" class="ps_unit_box_add n_btn34lg_add ml20"><span>添加新的学习单元</span></a></div>',
			        '<div id="ps_unit_box">' + attach_list_html + '</div>',
			        '</div>'
	         ].join("");
    	} else {
    		if (class_info.video_type == "video") {
    			var video_list_html = buildVideoListNode(class_info.videos),
    				class_box = [
    			        '<div class="s_videoCon video_class_box">',
    			        '<div class="s_inner"><div class="s_i_hd">',
    			        IsTeacher > 0 ? '' : '<a href="javascript:;" class="n_btn34lg_add mr15 pickVideos"><span>从视频库中选择</span></a>',
    			        IsTeacher > 0 ? '' : '<span class="s_i_hd_tips">未上传的视频请先上传至视频库 <a target="_blank" href="/?mod=video&act=upload&do=show' + authorizeUri + '" class="c_0065cb">上传视频</a></span>',
    			        '</div>' + video_list_html + '</div></div>'         
    	            ].join("");
    		} else {
    			var class_box = [
                    '<div class="s_videoCon outsite_link_box">',
                    '<div class="s_inner"><div class="s_i_hd"><div class="s_i_hd_notice clearfix">',
                    '<div class="fl"><img src="http://res.ckimg.com/sites/www/v2/images/public/ico_warning_16x16.png" alt=""></div>',
                    '<div class="fl"><span>请确保你对所添加链接拥有完全的版权</span></div></div></div>',
                    '<div class="s_i_bd clearfix"><form action="" class="s_i_form clearfix"><div class="formItem">',
                    '<label for="" class="form_label"><i>*</i><span>视频链接：</span></label><div class="form_field">',
                    '<input type="text" value="' + class_info.video_id + '" class="form_text videosrc" style="width:620px;"></div></div></form></div></div></div>'
                ].join("");
    		}
    	}
	}
	var html = [
		'<div class="item editTitleBox" sectionidx="'+class_info.class_index+'" cid="'+class_info.cid+'" stepid="'+class_info.step_id+'" style="display:none">',
		'<span class="i_num">第'+class_info.order+'节</span>',
		'<div class="i_con">',
		'<div class="pr clearfix mt7">',							
		'<input type="text" value="'+class_info.class_name+'" class="form_text w500 fl" id="class_name_text">',
		'</div></div></div>',
        '<div class="subBox editContentBox" style="display:none">',
        '<div class="subBox_c">',
        Individuation == 1 ? '<div class="subPoint"><input type="hidden" name="klid" id="select_kl_id" value="'+class_info.klid+'" /><div class="pr clearfix mt7 b"><span class="fl"><span id="select_kl_text" style="line-height: 35px;">'+class_info.knowledge+'</span></span><span><a href="javascript:void(0);" id="add_knowledge" class="n_btn34lg_add add_knowledge ml5">修改关联知识点</a></span></div></div>' : '',
		'<div class="pr mb10 clearfix">',
		'<textarea class="textarea500 fl" name="" id="" cols="" rows="">'+class_info.brief+'</textarea>',
		'</div>'+class_box,
		'<div class="mb10 mt15">',
		Course1V1 == false && Individuation == 0 ? (class_info.trail_flag == 2 ? '<label><input type="checkbox" checked="checked" class="mr5 free_trial">' : '<input type="checkbox" class="mr5 ">') : '',
		Course1V1 == false && Individuation == 0 ? '本节允许免费试听，学生无需购买就可以免费学习整节课程。</label>' : '',
		'</div><div class="mt20 mb25">',
		Individuation == 0 ? '<a class="n_btn34g mr20 submit_section" href="javascript:;">保存</a>' : '',
		Individuation == 1 ? '<a class="n_btn34g mr20 submit_is_section" href="javascript:;">保存</a>' : '',
		'<a class="n_btn34gr_b" href="javascript:;">取消</a>',
		'</div></div></div>'
	].join("");
	return html;
}

var buildVideoListNode = function(videos){
	var html = [
            '<div class="s_i_bd">',
            '<ul class="ul_s_i clearfix">'
	    ].join('');
	for(var i=0; i<videos.length; i++){
		html += [
	        '<li vid="'+videos[i].vid+'"><div class="s_i_picBox"><img alt="" src="'+videos[i].thumb+'">',
			'<p>'+videos[i].name+'</p><a class="s_i_close" href="javascript:;"></a></div></li>'
			].join('');
	}
	html += '</ul><div class="c_999 mb20">你可以通过拖拽改变以下视频的前后顺序。</div></div>';
	return html;
}

//个性化学习 课件节点
var buildCoursewareListNode = function(unit, coursewares) {
	var html  = '';
		html += '<ul class="items-list clearfix" unit="'+ unit +'">';
	for (var i = 0; i < coursewares[unit].length; i++) {
		var type = coursewares[unit][i].aid > 0 ? 1 : 2;
		html += [
	        type == 1 ? '<li vid="0" aid="' + coursewares[unit][i].aid +'"  type="' + type + '" cn="" ico="' + coursewares[unit][i].ico + '" class="clearfix type-' + type + ' filtrate">' : '<li vid="' + coursewares[unit][i].vid +'" aid="0" type="' + type + '" cn="" ico="" class="clearfix type-' + type + ' filtrate">',
	        '<div class="left-part">',
	        type == 1 ? '<span class="ico_' + coursewares[unit][i].ico + '"></span>' : '<img width="90" height="67" alt="" src="' + coursewares[unit][i].thumb + '">',
	        '</div><div class="right-part">' + coursewares[unit][i].name + '</div>',
	        '<a class="cell-item-del" href="javascript:;"></a>',
	        '</li>'
		].join('');
	}
	html += '<li class="type-3 selectVideos" unit="'+ unit +'"><div class="inner"><i></i>添加视频</div></li>';
	html += '<li class="type-3 selectCoureswares"  unit="'+ unit +'"><div class="inner"><i></i>添加课件</div></li>';
	html += '</ul>';
	return html;
}

var buildUnitListNode = function(unit, coursewares) {
	var html  = '';
		html += '<ul class="items-list clearfix" unit="'+ unit +'">';
	for (var i = 0; i < coursewares[unit].length; i++) {
		var type = coursewares[unit][i].aid > 0 ? 1 : 2;
		html += [
	        type == 1 ? '<li vid="0" aid="' + coursewares[unit][i].aid +'"  type="' + type + '" cn="" ico="' + coursewares[unit][i].ico + '" class="clearfix type-' + type + ' filtrate">' : '<li vid="' + coursewares[unit][i].vid +'" aid="0" type="' + type + '" cn="" ico="" class="clearfix type-' + type + ' filtrate">',
	        '<div class="left-part">',
	        type == 1 ? '<span class="ico_' + coursewares[unit][i].ico + '"></span>' : '<img width="90" height="67" alt="" src="' + coursewares[unit][i].thumb + '">',
	        '</div><div class="right-part">' + coursewares[unit][i].name + '</div>',
	        '</li>'
		].join('');
	}
	html += '</ul>';
	return html;
}

var buildAttachListNode = function(attachs){
	var html = [
            '<div id="selectedCourseware" class="s_i_hd">',
            '<ul class="s_c_ulBox clearfix">'
	    ].join('');
	if(typeof(attachs) != 'undefined') {
	for(var i=0; i<attachs.length; i++){
		html += [
	        '<li aid="'+attachs[i].aid+'">',
	        '<div id="courseware_'+attachs[i].aid+'" class="s_c_oCourseBox" title="'+attachs[i].name+'" ico="'+attachs[i].type+'" cn="" coursewareid="'+attachs[i].aid+'">',
	        '<div class="in_type"><img src="http://res.ckimg.com/sites/www/v2/images/public/kj_course/kj_'+attachs[i].type+'.png" alt=""></div>',
	        '<div class="in_txt"><p id="ajaxCwTitle_'+attachs[i].aid+'" class="p1 f14">'+attachs[i].name+'</p></div>',
	        '<div class="in_edit"><a cwid="'+attachs[i].aid+'" class="editCourseware" href="javascript:;">编辑</a><a href="/?mod=course&amp;act=courseware&amp;do=download&amp;coursewareid='+attachs[i].aid+'" target="_blank">下载</a><a cwid="'+attachs[i].aid+'" class="delCourseware" href="javascript:;">删除</a></div>',
			'</div></li>'
			].join('');
	}
	}
	html += '</ul></div>';
	return html;
}

var isUniqueCourseware = function(coursewareid, type) {
	for (var key in Coureswares) {
		if (Coureswares[key] != null) {
			for (var ckey in Coureswares[key]) {
				if (type == psstudyType.video) {
					if (Coureswares[key][ckey].vid == coursewareid) {
						return true;
					}
				} else if (type == psstudyType.attach) {
					if (Coureswares[key][ckey].aid == coursewareid) {
						return true;
					}
				}
			}
		}
	}
	return false;
}

var buildItemNode = function(data, class_info, order){
	var html = [
		'<div sectionidx="'+data.ClassIndex+'" cid="'+data.CID+'" stepid="'+data.StepID+'" class="item itemRow">',
		'<div class="set_order"><a href="javascript:;" class="move_u"></a>',
		'<a href="javascript:;" class="move_d"></a>',
		'</div><span class="i_num">第'+order+'节</span>',
		'<div class="i_con"><h3>'+class_info.class_name+'</h3></div><ul class="i_extra">',
		class_info.study_type == studyType.curr || class_info.study_type == studyType.live ? '<li>'+class_info.prelect_start_time+'</li>' : class_info.video_type == 'outsite_link' ? '<li>外部视频</li>' : (class_info.study_type == studyType.offline || Individuation == 1) ? '' : '<li>' + data.VideoTimeLength + '</li>',
		class_info.trail_flag == 2 ? '<li><i title="试听" class="iMusic"></i></li>' : '',
		class_info.study_type == studyType.curr || class_info.study_type == studyType.live ? '<li><i title="直播课" class="iVideo"></i></li>' : (class_info.study_type != studyType.offline) ? '<li><i title="视频课" class="iMedia"></i></li>' : '',
		class_info.study_type == studyType.live ? '<li><i class="i-ico-live" title="live直播">live</i></li>' : '',
		'</ul><ul class="i_edit">',
		IsTeacher > 0 ? '' : '<li><a class="c_add" href="javascript:;">插入</a></li>',
		'<li><a class="c_edit" href="javascript:;">编辑</a></li>',
		IsTeacher > 0 ? '' : '<li><a class="c_del" href="javascript:;">删除</a></li>',
		'</ul><a href="javascript:;" class="i_e_up">展开</a></div>'
	].join("");
	
	switch (parseInt(class_info.study_type)) {
		case studyType.live :
		case studyType.curr :
			var	curr_html = [
	    		'<div style="display:none;" id="section_'+data.CID+'" class="subBox" live='+class_info.study_type+'>',
				'<div class="subBox_c">',
				'<div class="conTxt"><p>'+class_info.brief+'</p></div>',
				'<ul class="ulLesson mt30">',
				'<li><span class="lab">直播时间：</span><span class="fb">'+class_info.prelect_start_time+'</span></li>',
				'<li><span class="lab">课程时长：</span><span class="fb">'+formatClassTimeLength(class_info.prelect_time_length)+'</span></li>',
				'<li><span class="lab">讲　　师：</span>',
				'<span><img width="24px" class="picTeacher" src="'+class_info.teacher_pic+'" title="'+class_info.teacher_name+'" uid="'+class_info.teacher_uid+'" alt=""></span>',
				' <span class="fb">'+class_info.teacher_name+'</span>',
				'</li></ul></div></div>'
	    	].join("");
			html = html + curr_html;
			break;
		case studyType.offline :
			var offlineinfo = '',
			    separator   = '';
			if (data.OfflineInfo.length > 0) {
				$.each(data.OfflineInfo, function(i, item) {
					offlineinfo += separator + '<span offline="'+item.id+'" class="fb address">'+item.address+'</span>';
					separator = '，';
				});
			}
			var	curr_html = [
	    		'<div style="display:none;" id="section_'+data.CID+'" class="subBox" live='+class_info.study_type+'>',
				'<div class="subBox_c">',
				'<div class="conTxt"><p>'+class_info.brief+'</p></div>',
				'<ul class="ulLesson mt30">',
				'<li><span class="lab">上课时间：</span>',
				'<span class="fb starttime">'+data.PrelectStartTime+'</span> 至 ',
				'<span class="fb endtime">'+data.PrelectEndTime+'</span></li>',
				'<li><span class="lab">上课地点：</span>',
				''+offlineinfo+'',
				'</li></ul></div></div>'
	    	].join("");
			html = html + curr_html;
			break;
		case studyType.video :
			if (class_info.video_type == "outsite_link") {
				var video_html = [
	                '<div class="subBox" style="display:none;" id="section_'+data.CID+'">',
	                '<div class="subBox_c"><div class="conTxt"><p>'+class_info.brief+'</p></div>',
					'<div class="mt20 mb20"><span class="fb">视频链接：</span>',
					'<a class="video_link" href="'+class_info.video_id+'" target="_blank">'+class_info.video_id+'</a></div></div></div>'
				].join("");
			} else {
				if (Individuation == 1) {
					var	video_html = [
	     				'<div class="subBox" id="section_'+data.CID+'" style="display:none">',
	     				'<div class="subBox_c">',
	     				'<div style="margin:0 0 17px;" class="conKnowledge"><p klid="'+class_info.klid+'">'+class_info.knowledge+'</p></div>',
	     				'<div class="conTxt" style="display:none;"><p>'+class_info.brief+'</p></div>'
	     			].join("");
					
					var attach_list_html = '',
	    		        attach_list_head = '<div class="cell-item-wrap mb20">';
	    		   
	    			if (class_info.attachs[1] != '') {
	    				attach_list_html += attach_list_head;
	    				attach_list_html += '<div class="mb10">学习单元1</div>';
	    				attach_list_html += buildUnitListNode(1, class_info.attachs);
	    				attach_list_html += '</div>';
	    			}
	    			if (class_info.attachs[2] != '') {
	    				attach_list_html += attach_list_head;
	    				attach_list_html += '<div class="mb10">学习单元2</div>';
	    				attach_list_html += buildUnitListNode(2, class_info.attachs);
	    				attach_list_html += '</div>';
	    			}
	    			if (class_info.attachs[3] != '') {
	    				attach_list_html += attach_list_head;
	    				attach_list_html += '<div class="mb10">学习单元3</div>';
	    				attach_list_html += buildUnitListNode(3, class_info.attachs);
	    				attach_list_html += '</div>';
	    			}
	   				video_html += attach_list_html + '';
				} else {
					var	video_html = [
	     				'<div class="subBox" id="section_'+data.CID+'" style="display:none">',
	     				'<div class="subBox_c">',
	     				'<div class="conTxt"><p>'+class_info.brief+'</p></div>',
	     				'<ul class="uPicList clearfix">'
	     			].join("");
					
					for (var i = 0; i < class_info.videos.length; i++) {
		   				video_html += '<li vid="'+class_info.videos[i].vid+'"><a href="javascript:;" title="'+class_info.videos[i].name+'" class="pic"><img width="90" height="68" src="'+class_info.videos[i].thumb+'"></a><p class="txt">'+class_info.videos[i].name+'</p></li>';
		   			}
		   			video_html += '</ul>';
		   			video_html += '</div></div>';
				}
			}
			html = html + video_html;
			break;
	}
	return html;
}

var getClassInfoFromNode = function($add_item, $add_box){
	var class_info = {
		"study_type"		: $add_item.find("i.iMedia").length > 0 ? studyType.video : studyType.curr,
		"trail_flag"		: $add_item.find("i.iMusic").length > 0 ? 2 : 1,
		"class_index"		: $add_item.attr('sectionidx'),
		"cid"				: $add_item.attr('cid'),
		"step_id"			: $add_item.attr('stepid'),
		"class_name"		: $add_item.find("h3").text(),
		"order"				: $add_item.find("span.i_num").text().match(/\d+/),
		"brief"				: $add_box.find("div.conTxt>p").text()
	}
	
	$add_box = $("#section_"+$add_item.attr('cid'));
	class_info.study_type = $add_box.attr('live');
	
	if(class_info.study_type == studyType.curr || class_info.study_type == studyType.live){
		class_info.prelect_start_time = $add_box.find("ul.ulLesson>li").eq(0).find("span.fb").text().match(/^\d{4}年\d{2}月\d{2}日 \d{2}:\d{2}/);
		class_info.prelect_time_length = getCurrClassTimeLenth($add_box.find("ul.ulLesson>li").eq(1).find("span.fb").text());
		class_info.teacher_pic = $add_box.find("img.picTeacher").attr("src");
		class_info.teacher_name = $add_box.find("img.picTeacher").attr("title");
		class_info.teacher_uid = $add_box.find("img.picTeacher").attr("uid");
	} else if (class_info.study_type == studyType.offline) {
		//上课时间
		class_info.prelect_start_time = $add_box.find("ul.ulLesson>li").eq(0).find("span.fb.starttime").text().match(/^\d{4}年\d{2}月\d{2}日 \d{2}:\d{2}/);
		class_info.prelect_end_time   = $add_box.find("ul.ulLesson>li").eq(0).find("span.fb.endtime").text().match(/^\d{4}年\d{2}月\d{2}日 \d{2}:\d{2}/);
		//上课地点
		var offlines = [];
		$add_box.find("ul.ulLesson>li").find(".address").each(function(){
			offlines.push($(this).attr('offline'));
		});
		class_info.offlines = offlines.join(',');
	} else {
		//个性化学习
		if (Individuation == 1) {
			Coureswares    = [];
			Coureswares[1] = [];
			Coureswares[2] = [];
			Coureswares[3] = [];
			
			class_info.knowledge = $add_box.find("div.conKnowledge>p").text();
			class_info.klid      = $add_box.find("div.conKnowledge>p").attr('klid');
			
			if ($add_box.find("ul.items-list").length > 0) {
				var attachs = [],
					$addAttachList = $add_box.find("ul.items-list>li");
				
				if ($addAttachList.length > 0) {
					$.each($addAttachList, function(idx, item) {
						var unit         = $(item).parent().attr('unit');
						var attach       = { 'vid' : 0, 'thumb' : '', 'name' : '', 'type' : '', 'ico' : '', 'aid' : 0, 'cn' : '' };
							attach.vid   = $(item).attr('vid');
							attach.aid   = $(item).attr('aid');
							attach.name  = $(item).find('.right-part').text();
							attach.thumb = $(item).find('img').attr('src');
							attach.type  = $(item).attr('ps_type');
							attach.ico   = $(item).attr('ico');
							attach.cn    = $(item).attr('cn');
						Coureswares[unit].push(attach);
					});
				}
				class_info.attachs = Coureswares;
			}
		} else {
			if ($add_box.find("ul.uPicList").length > 0) {
				var videos = [],
					vids   = [],
					$addVideoList = $add_box.find("ul.uPicList>li");
				if ($addVideoList.length > 0) {
					$.each($addVideoList, function(idx, item) {
						vids.push($(item).attr('vid'));
						var video   = {'vid':0, 'thumb':'', 'name':''}
							video.vid   = $(item).attr('vid');
							video.name  = $(item).find('p').text();
							video.thumb = $(item).find('img').attr('src');
						videos.push(video);
					});
				}
				class_info.video_id   = vids.join(',');
				class_info.videos     = videos;
				class_info.video_type = "video";
			} else {
				class_info.video_id   = $add_box.find("a.video_link").attr("href");
				class_info.video_type = "outsite_link";
			}
		}
	}
	return class_info;
}

var savePart = function($add_box, op){	
	if (op == partOpCode.add){
		var title = filterTitle($add_box.find("input").val()),
			stepBoxes = $("#CourseDanceBox div.sedu_t"),
			stepIdxTmp = [];
		if(stepBoxes.length > 0){
			$.each(stepBoxes, function(i, n){
				stepIdxTmp.push($(n).attr('stepIdx'));
			});
			var step_index = Math.max.apply(Math, stepIdxTmp)+1;
		}else{
			var step_index = 1;
		}
	}else if(op == partOpCode.edit){
		var title		= filterTitle($add_box.find("input").val()),
			step_index	= $add_box.attr("stepidx"),
			step_id		= $add_box.attr("stepid");
	}else{
		var step_index	= $add_box.attr("stepidx"),
			step_id		= $add_box.attr("stepid");
	}
	var	postStr = [
       "courseid="+encodeURIComponent(CourseID),
       op == partOpCode.add ? "step_id=0" : "step_id="+step_id,
       "step_index="+encodeURIComponent(step_index),
       op == partOpCode.del ? "" : "name="+encodeURIComponent(title),
       "op="+op,
	].join('&');
	
	
	if(IsTeacher){
		var url = "/?mod=course&act=create&do=saveDetail&step=part&isteacher=1&random="+Math.random();
	}else{
		var url = "/?mod=course&act=create&do=saveDetail&step=part"+authorizeUri+"&random="+Math.random();
	}
	$.ajax({
		url : url,
		type : "post",
		data : postStr,
		dataType : "json",
		async : true,
		success : function(rs){
			if(rs.code > 0){
				if(op == partOpCode.add || op == partOpCode.edit){
					if (op == partOpCode.edit){
						var part_order = parseInt($add_box.prevAll("div.sedu_t").length + 1);
					}else{
						var part_order = parseInt(stepBoxes.size()+1);
					}
					var html = [
			           '<div style="display:none" class="sedu_t" stepid="'+rs.data.StepID+'" stepidx="'+rs.data.StepIndex+'">',
			           '<h2>第 '+part_order+' 章：'+title+'</h2>',
			           '<ul class="i_edit">',
			           '<li><a href="javascript:;" class="c_edit edit_part">编辑</a></li>',
			           '<li><a href="javascript:;" class="c_del del_part">删除</a></li>',
			           '</ul></div>',
		        	   op == partOpCode.add ? '<div class="sedu_tBox" stepidx="'+rs.data.StepIndex+'" stepid="'+rs.data.StepID+'">' : '',
        			   op == partOpCode.add ? '<div class="item_add">' : '',
					   op == partOpCode.add ? '<div class="addBox"><a href="javascript:;" class="a_add add_section ml25">添加一讲</a></div>' : '',
					   op == partOpCode.add ? '</div></div>' : ''
		            ].join('');
					$add_box.fadeOut('fast', function(){
						if (op == partOpCode.add){
							var $add_part_box = $add_box.next("div.sedu_t_add"); 
							$(this).replaceWith(html);
							$add_part_box.prev().prev("div.sedu_t").fadeIn('fast');
							$add_part_box.fadeIn('fast');
						}else{
							var $dirty_item = $(this).next("div.sedu_t:hidden");
							$(this).replaceWith(html);
							$dirty_item.prev("div.sedu_t").fadeIn("fast");
							$dirty_item.remove();
						}
					});
				}else{
					$add_box.next("div.sedu_tBox").slideUp("fast", function(){
						$sedu_tBox = $(this);
						$add_box.slideUp("fast", function(){
							$(this).remove();
							$sedu_tBox.remove();
							resetPartNu();
						});
					});
				}
			}else{
				$.ckAlert({message:rs.data});
			}
		}
	})
}

var saveSection = function($add_box, $add_item, op){
	if(op == sectionOpCode.del){
		var postStr = [
           'courseid='+encodeURIComponent(CourseID),
           'step_id='+encodeURIComponent($add_item.attr("stepid")),
           'cid='+encodeURIComponent($add_item.attr("cid")),
           'class_index='+encodeURIComponent($add_item.attr('sectionidx')),
           'op='+encodeURIComponent(sectionOpCode.del),
           $add_box.find("div.live_class_box").length > 0 ? 'teacher_uid='+encodeURIComponent($add_box.find("img.picTeacher").attr('uid')) : ''
        ].join('&');
	} else {
		var $submitBtn = $add_box.find("submit_section");
		if ($add_item.attr("type") == "insert_before") {
			var class_index = $add_item.next().next("div.itemRow").attr("sectionidx");
		} else if ($add_item.attr("type") == "insert_after") {
			var class_index = parseInt($add_item.prev().prev("div.itemRow").attr("sectionidx")) + 1;
		} else {
			var class_index = op == sectionOpCode.add ? getMaxSectionIdx() : $add_item.attr("sectionidx");
		}
		if ($add_box.find("div.live_class_box").length > 0) {
			//切换直播模式
			var live_model = studyType.curr;
			if (studyType.curr == 1 && Live == 1 || (IsAuthorize == 1 && Live == 1)) {
				live_model = $add_box.find("input[name='live_model']:checked").val();
			}
			var class_info = {
					'course_id'		: CourseID,
					'step_id'		: $add_item.parent("div.sedu_tBox").attr("stepid"),
					'class_index'	: class_index,
					'study_type'	: live_model,
					'trail_flag'	: $add_box.find("input:checkbox[name!='save_flag']").attr('checked')=='checked' ? 2 : 1,
					'save_flag'		: ($add_box.find("input:checkbox[name='save_flag']").length > 0 && !$add_box.find("input:checkbox[name='save_flag']").attr('checked')) ? 2 : 1,
					'prelect_start_time'	: $add_box.find("input.ymd").val()+" "+$add_box.find("input.hi").val(),
					'prelect_time_length'	: $add_box.find("select").val(),
					'teacher_uid'	: $add_box.find("img.s_i_picTeacher").attr('uid'),
					'teacher_name'	: $add_box.find("img.s_i_picTeacher").attr('title'),
					'class_name'	: filterTitle(removeHTMLTag($add_item.find("input").val())),
					'brief'			: removeHTMLTag($add_box.find("textarea").val()),
					'teacher_pic'	: $add_box.find("img.s_i_picTeacher").attr('src'),
					'cid'			: op == sectionOpCode.add ? 0 : $add_item.attr("cid")
				}
				postStr = [
		          'courseid='+encodeURIComponent(class_info.course_id),
		          'step_id='+encodeURIComponent(class_info.step_id),
		          'video_id=',
		          'cid='+class_info.cid,
		          'class_index='+encodeURIComponent(class_info.class_index),
		          'study_type='+encodeURIComponent(class_info.study_type),
		          'trail_flag='+class_info.trail_flag,
		          'save_flag='+class_info.save_flag,
		          'prelect_start_time='+encodeURIComponent(class_info.prelect_start_time),
		          'prelect_time_length='+encodeURIComponent(class_info.prelect_time_length),
		          'teacher_uid='+encodeURIComponent(class_info.teacher_uid),
		          'teacher_name='+encodeURIComponent(class_info.teacher_name),
		          'class_name='+encodeURIComponent(class_info.class_name),
		          'brief='+encodeURIComponent(class_info.brief),
		          'op='+op
	           ].join('&');
		} else if($add_box.find("div.video_class_box").length > 0) {
			var vids = [],
				videos = [];
			$.each($add_box.find("div.s_i_bd li"), function(idx, item) {
				vids.push($(item).attr('vid'));
				var video = {'vid':0, 'thumb':'', 'name':''}
				video.vid = $(item).attr('vid');
				video.name = $(item).find('p').text();
				video.thumb = $(item).find('img').attr('src');
				videos.push(video);
			});
			var	class_info = {
					'course_id'		: CourseID,
					'step_id'		: $add_item.parent("div.sedu_tBox").attr("stepid"),
					'class_index'	: class_index,
					'study_type'	: studyType.video,
					'trail_flag'	: $add_box.find("input:checkbox[name!='save_flag']").attr('checked')=='checked' ? 2 : 1,
					'save_flag'		: ($add_box.find("input:checkbox[name='save_flag']").length > 0 && !$add_box.find("input:checkbox[name='save_flag']").attr('checked')) ? 2 : 1,
					'video_id'		: vids.join(','),
					'class_name'	: filterTitle(removeHTMLTag($add_item.find("input").val())),
					'brief'			: removeHTMLTag($add_box.find("textarea").val()),
					'videos'		: videos,
					'video_type'	: "video",
					'cid'			: op == sectionOpCode.add ? 0 : $add_item.attr("cid")
				},
				postStr = [
		          'courseid='+encodeURIComponent(class_info.course_id),
		          'step_id='+encodeURIComponent(class_info.step_id),
		          'video_id='+encodeURIComponent(class_info.video_id),
		          'cid='+class_info.cid,
		          'class_index='+encodeURIComponent(class_info.class_index),
		          'study_type='+encodeURIComponent(class_info.study_type),
		          'trail_flag='+class_info.trail_flag,
		          'save_flag='+class_info.save_flag,
		          'prelect_start_time=0',
		          'prelect_time_length=0',
		          'teacher_uid=0',
		          'teacher_name=0',
		          'class_name='+encodeURIComponent(class_info.class_name),
		          'brief='+encodeURIComponent(class_info.brief),
		          'op='+op
	           ].join('&');
		} else if($add_box.find("div.outsite_link_box").length > 0) {
			var class_info = {
					'course_id'		: CourseID,
					'step_id'		: $add_item.parent("div.sedu_tBox").attr("stepid"),
					'class_index'	: class_index,
					'study_type'	: studyType.video,
					'video_id'		: correctQuoteVideoSrc(removeHTMLTag($add_box.find("input.videosrc").val())),
					'trail_flag'	: $add_box.find("input:checkbox").attr('checked')=='checked' ? 2 : 1,
					'class_name'	: filterTitle(removeHTMLTag($add_item.find("input").val())),
					'brief'			: removeHTMLTag($add_box.find("textarea").val()),
					'teacher_pic'	: $add_box.find("img.s_i_picTeacher").attr('src'),
					'video_type'	: "outsite_link",
					'cid'			: op == sectionOpCode.add ? 0 : $add_item.attr("cid")
				},
				postStr = [
		          'courseid='+encodeURIComponent(class_info.course_id),
		          'step_id='+encodeURIComponent(class_info.step_id),
		          'video_id='+encodeURIComponent(class_info.video_id),
		          'cid='+class_info.cid,
		          'class_index='+encodeURIComponent(class_info.class_index),
		          'study_type='+encodeURIComponent(class_info.study_type),
		          'trail_flag='+class_info.trail_flag,
		          'prelect_start_time=0',
		          'prelect_time_length=0',
		          'teacher_uid=0',
		          'teacher_name=0',
		          'class_name='+encodeURIComponent(class_info.class_name),
		          'brief='+encodeURIComponent(class_info.brief),
		          'op='+op
	           ].join('&');
		} else if ($add_box.find("div.offline_class_box").length > 0) {
			
			var offlineids = [];
			$('.addr-list li input:checkbox').each(function() {
				if ($(this).attr("checked") == "checked") {
					offlineids.push($(this).val());
				}
			});
			
			if (offlineids.length <= 0) {
				$.ckAlert({message:"您还未设置上课地点！"});
				return;
			}
			
			var class_info = {
					'course_id'		: CourseID,
					'step_id'		: $add_item.parent("div.sedu_tBox").attr("stepid"),
					'class_index'	: class_index,
					'study_type'	: studyType.offline,
					'offline_ids'   : offlineids.join(','),
					'trail_flag'	: $add_box.find(".free_trial").attr('checked') == 'checked' ? 2 : 1,
					'class_name'	: filterTitle(removeHTMLTag($add_item.find("input").val())),
					'brief'			: removeHTMLTag($add_box.find("textarea").val()),
					'start_datetime': $('#offline_start_date').val()+" "+$('#offline_start_time').val(),
					'end_datetime'  : $('#offline_end_date').val()+" "+$('#offline_end_time').val(),
					'cid'			: op == sectionOpCode.add ? 0 : $add_item.attr("cid")
				},
				postStr = [
		          'courseid='+encodeURIComponent(class_info.course_id),
		          'step_id='+encodeURIComponent(class_info.step_id),
		          'video_id='+encodeURIComponent(class_info.video_id),
		          'offline_ids='+encodeURIComponent(class_info.offline_ids),
		          'cid='+class_info.cid,
		          'class_index='+encodeURIComponent(class_info.class_index),
		          'study_type='+encodeURIComponent(class_info.study_type),
		          'trail_flag='+class_info.trail_flag,
		          'prelect_start_time=0',
		          'prelect_time_length=0',
		          'teacher_uid=0',
		          'teacher_name=0',
		          'offline_start_datetime='+encodeURIComponent(class_info.start_datetime),
		          'offline_end_datetime='+encodeURIComponent(class_info.end_datetime),
		          'class_name='+encodeURIComponent(class_info.class_name),
		          'brief='+encodeURIComponent(class_info.brief),
		          'op='+op
	           ].join('&');
		} else {
			 $.ckAlert({message:"您还未安排课程，请先安排课程！"});
			 return false;
		}
		if($submitBtn.attr('disabled') == 1){
			return false;
		}
	}
	if (IsTeacher) {
		var url = "/?mod=course&act=create&do=saveDetail&step=section&isteacher=1&random="+Math.random();
	} else {
		var url = "/?mod=course&act=create&do=saveDetail&step=section"+authorizeUri+"&random="+Math.random();
	}
	var tipsBox = null;

	$.ajax({
		url : url,
		type : "post",
		data : postStr,
		dataType : "json",
		async : true,
		beforeSend : function() {
			op != sectionOpCode.del && $submitBtn.attr('disabled', '1');
			tipsBox = $.ckTipsBoxy({
				message : "数据提交中...",
				mask : true,
				type : "loading"
			});
		},
		success : function(rs) {
			tipsBox.cancel();
			if (rs.code > 0) {
				if (op == sectionOpCode.del) {
					var $partNode = $add_item.parent("div.sedu_tBox");
					if ($add_box.css("display") == "none") {
						$add_item.fadeOut("fast", function(){
							$(this).remove();
							$add_box.remove();
							resetSectionNu($partNode);
						})
					} else {
						$add_box.slideUp("fast", function(){
							$(this).remove();
							$add_item.fadeOut("fast", function(){
								$(this).remove();
								resetSectionNu($partNode);
							})
						})
					}
				} else {
					var order = $add_item.find("span.i_num").text().match(/\d+/);
					var html  = buildItemNode(rs.data, class_info, order);
					$add_box.slideUp("fast", function() {
						$add_item.fadeOut("fast", function() {
							if (op == sectionOpCode.edit) {
								$("#section_"+rs.data.CID).prev("div.itemRow").remove();
								$("#section_"+rs.data.CID).remove();
							} else {
								$add_box.next("div.item_add").fadeIn("fast");
							}
							$add_item.replaceWith(html);
							$("#section_"+rs.data.CID).slideDown("fast");
							$add_box.remove();
							if ($add_item.attr("type") != "undefined") {
								resetSectionIdx($("#section_"+rs.data.CID));
							}
						});
					});
				}
			} else {
				op != sectionOpCode.del && $submitBtn.removeAttr('disabled');
				switch (rs.code) {
//					case -2 : $("#addSectionTitle_"+section.StepID+" span.class_name").addClass('form_error').text(rs.data);
//							  $("#addSectionTitle_"+section.StepID+" input[name='class_name']").addClass("form_text_error");
//							  break;
//					case -3 : $("#addSectionContent_"+section.StepID+" span.brief").addClass('form_error').text(rs.data);
//							  $("#addSectionContent_"+section.StepID+" textarea").addClass("form_text_error");
//							  break;
//					case -4 :
//					case -6 : $("#addSectionContent_"+section.StepID+" span.time").addClass('form_error').text(rs.data);
//							  break;
//					case -5 : $("#addSectionContent_"+section.StepID+" span.prelect_time_length").addClass('form_error').text(rs.data);
//							  break;
//					case -7 : $("#addSectionContent_"+section.StepID+" span.pickTeacher").addClass('form_error').text(rs.data);
//							  break;
					default : $.ckAlert({message:rs.data, width:360});
				}
			}
		}
	});
}

//个性化学习-保存视频或课件 S
var saveISSection = function($add_box, $add_item, op) {
	//删除操作
	if (op == sectionOpCode.del) {
		var postStr = [
           'courseid='    + encodeURIComponent(CourseID),
           'step_id='     + encodeURIComponent($add_item.attr("stepid")),
           'cid='         + encodeURIComponent($add_item.attr("cid")),
           'class_index=' + encodeURIComponent($add_item.attr('sectionidx')),
           'op='          + encodeURIComponent(sectionOpCode.del),
           $add_box.find("div.live_class_box").length > 0 ? 'teacher_uid=' + encodeURIComponent($add_box.find("img.picTeacher").attr('uid')) : ''
        ].join('&');
	} else {
		var $submitBtn = $add_box.find("submit_is_section"),
			tipsBox    = null;
		
		//获取单课节序号
		if ($add_item.attr("type") == "insert_before") {
			var class_index = $add_item.next().next("div.itemRow").attr("sectionidx");
		} else if ($add_item.attr("type") == "insert_after") {
			var class_index = parseInt($add_item.prev().prev("div.itemRow").attr("sectionidx")) + 1;
		} else {
			var class_index = op == sectionOpCode.add ? getMaxSectionIdx() : $add_item.attr("sectionidx");
		}
		//是否设置附件的标识
		var isCourseware = false;
		//设置单课节信息
		var	class_info = {
			'course_id'		: CourseID,
			'step_id'		: $add_item.parent("div.sedu_tBox").attr("stepid"),
			'class_index'	: class_index,
			'klid'			: $("#select_kl_id").val(),
			'knowledge'		: $("#select_kl_text").text(),
			'study_type'	: studyType.video,
			'trail_flag'	: $add_box.find("input:checkbox").attr('checked') == 'checked' ? 2 : 1,
			'class_name'	: filterTitle(removeHTMLTag($('#class_name_text').val())),
			'brief'			: removeHTMLTag($add_box.find("textarea").val()),
			'videos' 	  	: '',
			'cid'			: op == sectionOpCode.add ? 0 : $add_item.attr("cid")
		};
		if ($add_box.find("div.cell-item-wrap").length > 0) {
			var unit_vids = [];
			$.each($add_box.find("div.cell-item-wrap"), function(idx, item) {
				var vids = [];
				$.each($(item).find('li.filtrate'), function(unit_idx, unit_item) {
					if ($(unit_item).attr('vid') > 0) {
						var attach_id = $(unit_item).attr('type') + '-' + $(unit_item).attr('vid');
					} else if ($(unit_item).attr('aid') > 0) {
						var attach_id = $(unit_item).attr('type') + '-' + $(unit_item).attr('aid');
					}
					vids.push(attach_id);
				});
				var _vids = vids.join('_');
				unit_vids.push(_vids);
			});
			class_info.video_id = unit_vids;
			if (class_info.video_id != ',,') {
				isCourseware = true;
			}
		}
		//判断是否设置知识点
		if (!class_info.klid) {
//			$.ckAlert({message:"您还未选择知识点，请先选择知识点！"});
//			return false;
		}
		//判断是否设置学习单元
		if (!isCourseware){
			$.ckAlert({message:"您还未分配学习单元，请先分配学习单元！"});
			return false;
		} else {
			//初始化个性化学习单元数据
			Coureswares    = [];
			Coureswares[1] = [];
			Coureswares[2] = [];
			Coureswares[3] = [];
			
			if ($add_box.find("ul.items-list").length > 0) {
				var attachs = [],
					$addAttachList = $add_box.find("ul.items-list > li.filtrate");
				if ($addAttachList.length > 0) {
					$.each($addAttachList, function(idx, item) {
						var unit         = $(item).parent().attr('unit');
						var attach       = { 'vid' : 0, 'thumb' : '', 'name' : '', 'type' : '', 'ico' : '', 'aid' : 0, 'cn' : '' };
							attach.vid   = $(item).attr('vid');
							attach.aid   = $(item).attr('aid');
							attach.name  = $(item).find('.right-part').text();
							attach.thumb = $(item).find('img').attr('src');
							attach.type  = $(item).attr('ps_type');
							attach.ico   = $(item).attr('ico');
							attach.cn    = $(item).attr('cn');
						Coureswares[unit].push(attach);
					});
				} else {
					$.ckAlert({message:"您还未分配学习单元，请先分配学习单元！"});
					return false;
				}
				//自动单元调整策略
				autoUnitAdjust(Coureswares);
				class_info.attachs = Coureswares;
			}
			
			var postStr = [
		          'courseid='    + encodeURIComponent(class_info.course_id),
		          'step_id='     + encodeURIComponent(class_info.step_id),
		          'kl_id='       + encodeURIComponent(class_info.klid),
		          'kl_name='     + encodeURIComponent(class_info.knowledge),
		          'video_id='    + encodeURIComponent(class_info.video_id),
		          'cid='         + class_info.cid,
		          'class_index=' + encodeURIComponent(class_info.class_index),
		          'study_type='  + encodeURIComponent(class_info.study_type),
		          'trail_flag='  + class_info.trail_flag,
		          'class_name='  + encodeURIComponent(class_info.class_name),
		          'brief='       + encodeURIComponent(class_info.brief),
		          'prelect_start_time=0',
		          'prelect_time_length=0',
		          'teacher_uid=0',
		          'teacher_name=0',
		          'op=' + op
	           ].join('&');
		}
		if ($submitBtn.attr('disabled') == 1) {
			return false;
		}
	}
	//判断是否为教务老师
	if (IsTeacher) {
		var url = "/?mod=course&act=create&do=saveDetail&step=individuation&isteacher=1&random=" + Math.random();
	} else {
		var url = "/?mod=course&act=create&do=saveDetail&step=individuation" + authorizeUri + "&random=" + Math.random();
	}
	
	$.ajax({
		url         : url,
		type        : "post",
		data        : postStr,
		dataType    : "json",
		async       : true,
		beforeSend  : function(){
			op != sectionOpCode.del && $submitBtn.attr('disabled', '1');
			tipsBox = $.ckTipsBoxy({
				message : "数据提交中...",
				mask    : true,
				type    : "loading"
			});
		},
		success     : function(rs) {
			tipsBox.cancel();
			if (rs.code > 0) {
				if (op == sectionOpCode.del) {
					var $partNode = $add_item.parent("div.sedu_tBox");
					if ($add_box.css("display") == "none") {
						$add_item.fadeOut("fast", function() {
							$(this).remove();
							$add_box.remove();
							resetSectionNu($partNode);
						})
					} else {
						$add_box.slideUp("fast", function() {
							$(this).remove();
							$add_item.fadeOut("fast", function() {
								$(this).remove();
								resetSectionNu($partNode);
							})
						})
					}
				} else {
					var order = $add_item.find("span.i_num").text().match(/\d+/);
					var html = buildItemNode(rs.data, class_info, order);
					$add_box.slideUp("fast", function() {
						$add_item.fadeOut("fast", function() {
							if (op == sectionOpCode.edit) {
								$("#section_"+rs.data.CID).prev("div.itemRow").remove();
								$("#section_"+rs.data.CID).remove();
							} else {
								$add_box.next("div.item_add").fadeIn("fast");
							}
							$add_item.replaceWith(html);
							$("#section_"+rs.data.CID).slideDown("fast");
							$add_box.remove();
							if ($add_item.attr("type") != "undefined") {
								resetSectionIdx($("#section_"+rs.data.CID));
							}
						});
					});
				}
			} else {
				op != sectionOpCode.del && $submitBtn.removeAttr('disabled');
				switch (rs.code) {
					default : $.ckAlert({
						message:rs.data, 
						width:360
					});
				}
			}
		}
	});
}
//个性化学习-保存视频或课件 E

//线下课程 S
var setLocationCity = function(code) {
	if (code == 0) {
	    $('#idCity').empty();
	    $('#idCity').append('<option value="0">市区</option>');
	    return;
	}
	var obj = KK.province[code].Nodes;
	var str = '';
	$.each(obj, function(i, item){
		str += '<option value="'+item.Code+'">'+item.CodeName+'</option>';
	});
	$("#idCity").html(str);
}

var initLocation = function(code) {
	$.each(KK.province, function(pi, pv) {
		$.each(pv.Nodes, function(ci, cv) {
			if (code == 0) {
				setLocationCity(code);
			} else if (ci == code) {
				setLocationCity(pv.Code);
				$("#idProvince").find("option[value='"+pi+"']").attr("selected", true);
				$("#idCity").find("option[value='"+ci+"']").attr("selected", true);
			}
		});
	});
}

var getLocation = function(code) {
	var arr = [];
	$.each(KK.province, function(pi, pv) {
		$.each(pv.Nodes, function(ci, cv) {
			if (ci == code) {
				setLocationCity(pv.Code);
				arr['c'] = $("#idProvince").find("option[value='"+pi+"']").text();
				arr['a'] = $("#idCity").find("option[value='"+ci+"']").text();
			}
		});
	});
	return arr;
}

var checkCity = function(province, city) {
	if (!province) {
		return false;
	}
	if (!city) {
		return false;
	}
	return true;
};

var checkAddress = function(address) {
	if (!address) {
		return false;
	}
	return true;
};

var ajaxOfflineAddress = function(class_info) {
	//初始化所在地
	$.ajax({
		url:"/js/course/location.json",
		type:"get",
		dataType:"json",
		success:function(ret) {
			KK.province = ret;
			var options = '';
			options += '<option value="0">省/直辖市</option>';
			$.each(ret, function(i, item) {
				options += '<option value="'+item.Code+'">'+item.CodeName+'</option>';
			});
			$("#idProvince").html(options).live('change', function() {
				setLocationCity($(this).val());
			});
		}
	});
	$.ajax({
		url:"/?mod=course&act=offline&do=list&sid="+SID+"&authorize="+IsAuthorize+"&random="+Math.random(),
		type:"get",
		dataType:"json",
		success:function(offline) {
			var lis = '',
			    offlines = [];
			if (class_info != 0) {
				offlines = class_info.offlines.split(",");
				delOfflines = class_info.offlines.split(",");
			}
			$.each(offline.data, function(i, oitem) {
				var selected = false;
				var c = getLocation(oitem.City);
				lis += '<li class="clearfix" offlineid='+ oitem.OffLineID +' city='+ oitem.City +'><div class="addr"><label id="offline_'+ oitem.OffLineID +'">';
				$.each(offlines, function(j, id) {
					if (id == oitem.OffLineID) {
						selected = true;
						return false;
					}
				});
				if (selected) {
					lis += '<input type="checkbox" value="' + oitem.OffLineID + '" checked>';
				} else {
					lis += '<input type="checkbox" value="' + oitem.OffLineID + '">';
				}
				lis += '<i>'+ c.c + c.a +'</i><span>' + oitem.Address + '</span></label></div>';
				lis += '<div class="addr-edit"><a class="edit" href="javascript:;">编辑</a><span>|</span><a href="javascript:;" class="del">删除</a></div></li>';
				lis += '</li>';
			});
			$(".addr-list").html(lis);
		}
	});
}
//线下课程 E

var selectClass = function($selector, type){
	
	switch(type){
	case "live_class" : 
		var html = [
            '<div class="s_videoCon live_class_box" style="display:none">',
            '<div class="s_inner pb10">',
            '<div class="s_i_hd">',
            '<div class="s_i_hd_notice">',
            Course1V1 == true ? '' : '<div class="fl"><img alt="" src="http://res.ckimg.com/sites/www/v2/images/public/ico_warning_16x16.png"></div>',
            Course1V1 == true ? '' : '<div class="fl">',
            Course1V1 == true ? '' : '<p><span>你设定的限购人数大于直播教室的容量，当购买人数超过教室容量时，存在某些用户无法进入教室的风险。</span></p>',
            Course1V1 == true ? '' : '<p><a href="http://www.chuanke.com/?mod=help&act=index&do=showInfo&SID=211&HID=20&PID=345" target="_blank">了解详情&gt;&gt;</a></p></div>',
			'</div></div>',
			'<div class="s_i_bd">',
			'<form class="s_i_form clearfix" action="">',
			(Live == 1 || (IsAuthorize == 1 && Live == 1)) ? '<div class="formItem">' : '',
			(Live == 1 || (IsAuthorize == 1 && Live == 1)) ? '<label class="form_label" for="">' : '',
			(Live == 1 || (IsAuthorize == 1 && Live == 1)) ? '<i>*</i><span>直播模式：</span></label>' : '',
			(Live == 1 || (IsAuthorize == 1 && Live == 1)) ? '<div class="form_field">' : '',
			(Live == 1 || (IsAuthorize == 1 && Live == 1)) ? '<label class="mr20"><input type="radio" name="live_model" value="1" checked="checked" /> <span class="f12">实时直播</span></label>' : '',
			(Live == 1 || (IsAuthorize == 1 && Live == 1)) ? '<label><input type="radio" name="live_model" value="3" /><span class="f12"> Live直播</span></label>' : '',
		    (Live == 1 || (IsAuthorize == 1 && Live == 1)) ? '<span class="pr"> <a id="liveZBiHelp" href="javascript:;" class="liveZBiHelp i_help"> </a>' : '',
		    (Live == 1 || (IsAuthorize == 1 && Live == 1)) ?	'<div class="p-live-tips-wrap" style="display: none;"><dl class="p-live-tips"><dt><span class="fn">live直播：</span></dt><dd>一种适合于大量学员的直播方式，但相比实时直播，时间略有延迟。</dd><dd><i class="arrow-down"></i></dd></dl></div></span>' : '',
		    (Live == 1 || (IsAuthorize == 1 && Live == 1)) ?	'</div></div>' : '',
			'<div class="formItem">',
			'<label class="form_label" for="">',
			'<i>*</i><span>直播时间：</span></label>',
			'<div class="form_field">',
			'<input type="text" value="- 请选年、月、日 -" onClick="WdatePicker({dateFmt:\'yyyy年MM月dd日\',minDate:\'%y-%M-%d\', maxDate:\''+ExpiryTime+'\'})" class="form_text form_text_s_i ymd"> ',
			'<input type="text" value="- 请选则具体时间-" onClick="timepicker(this)" value="- 请选则具体时间 -" class="form_text form_text_s_i hi">',
			'</div><div style="text-indent:7em;" class="c_999">请谨慎设置直播课时间，以防学生在学习有效期内无法上直播课带来纠纷。</div></div>',
			'<div class="formItem">',
			'<label class="form_label" for="">',
			'<i>*</i><span>课程时长：</span></label>',
			'<div class="form_field">',
			'<select class="selt-kcsc" name="prelect_time_length">',
			'<option value="0">请选择</option>'+getTimeOptions(),
			'</select></div></div>',
			'<div class="formItem">',
			'<label class="form_label" for="">',
			'<i>*</i><span>选择老师：</span></label>',
			'<div class="form_field">',
			'<a class="n_btn30gr_b pickTeacher" href="javascript:;">选择老师</a>',
			'</div></div>',
			'<div class="f12 cb" style="display:'+SaveDisplay+';"><label><input type="checkbox" checked="checked" name="save_flag" value="1"/><span>以上视频免费试用数据保全服务</span>',
            '<span class="c_999">（该服务用于保护数字作品版权，请确保您有版权）</span><a class="i_help" href="http://www.chuanke.com/?mod=help&do=showInfo&SID=211&HID=20&PID=404" target="_blank"></a></label></div>',
			'</form></div></div>',
			'<a class="s_select close_box" href="javascript:;"></a></div>'
		].join("");
		break;
	case "video_class" : 
		var html = [
            '<div class="s_videoCon video_class_box" style="display:none">',
            '<div class="s_inner">',
            '<div class="s_i_hd">',	
            '<a class="n_btn34lg_add mr15 pickVideos" href="javascript:;"><span>从视频库中选择</span></a>',
            '<span class="s_i_hd_tips">未上传的视频请先上传至视频库 <a class="c_0065cb" href="/?mod=video&act=upload&do=show'+authorizeUri+'" target="_blank">上传视频</a></span>',
            '</div><div class="tc mt30">请为该视频课添加视频文件</div>',
            '<div class="f12 pb10 pl20" style="display:none;" id="video_save_tip"><label><input type="checkbox" checked="checked" name="save_flag" value="1"/><span>以上视频免费试用数据保全服务</span>',
            '<span class="c_999">（该服务用于保护数字作品版权，请确保您有版权）</span><a class="i_help" href="http://www.chuanke.com/?mod=help&do=showInfo&SID=211&HID=20&PID=404" target="_blank"></a></label></div>',
            '</div>',
            '<a class="s_select close_box" href="javascript:;"></a></div>'
        ].join("");
		break;
	case "offline_class" :
		var html = [
            '<div class="s_videoCon offline_class_box" style="display:none">',
            '<div class="s_inner">',
	            '<div class="form-wrap-xx clearfix">',
		            '<div class="formItem clearfix mb20" style="border-bottom:1px solid #dbdbdb;">',
		                '<div class="form_label">上课时间：</div>',
		                '<div class="form_field">',
		                    '<span class="pr mr15 ip-r">',
		                        '<input type="text" value="开始日期" onClick="WdatePicker({dateFmt:\'yyyy年MM月dd日\',minDate:\'%y-%M-%d\', maxDate:\''+ExpiryTime+'\'})" class="form_text date" id="offline_start_date">',
		                        '<span class="iptTips"></span>',
		                    '</span>',
		                    '<span class="pr mr15 ip-r">',
		                        '<input type="text" value="开始时间" onClick="timepicker(this)" class="form_text date" id="offline_start_time">',
		                        '<span class="iptTips"></span>',
		                    '</span>',
		                    '<span class="mr15">至</span>',
		                    '<span class="pr mr15 ip-r">',
		                        '<input type="text" value="结束日期" onClick="WdatePicker({dateFmt:\'yyyy年MM月dd日\',minDate:\'%y-%M-%d\', maxDate:\''+ExpiryTime+'\'})" class="form_text date" id="offline_end_date">',
		                        '<span class="iptTips"></span>',
		                    '</span>',
		                    '<span class="pr mr15 ip-r">',
		                        '<input type="text" value="结束时间" onClick="timepicker(this)" class="form_text date"  id="offline_end_time">',
		                        '<span class="iptTips"></span>',
		                    '</span>',
		                '</div>',
		                '<div style="text-indent:4em;" class="c_999">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;请谨慎设置线下课时间，以防学生在学习有效期内无法上线下课带来纠纷。</div>',
		            '</div>',
		            '<div class="formItem clearfix">',
		                '<div class="form_label">上课地点：</div>',
		                '<div class="form_field">',
			                '<ul class="addr-list"></ul>',
		                	'<div class="add-box" style="display:none;">',
			                	'<div class="mb15">',
		                            '<select name="" id="idProvince">',
		                                '<option value="">省/直辖市</option>',
		                            '</select>',
		                            '<select name="" id="idCity">',
		                                '<option value="">市区</option>',
		                            '</select>',
		                        '</div>',
		                        '<div class="mb15">',
		                            '<span class="pr ip-r">',
		                                '<input type="text" class="form_text offline_address" style="width: 514px;">',
		                                '<span class="iptTips offline_address_tips">详细地址</span>',
		                            '</span>',
		                        '</div>',
		                        '<div>',
	                            	'<a href="javascript:;" class="n_btn34lg mr20 offline_address_submit">保存</a >',
	                            	'<a href="javascript:;" class="n_btn34lg offline_address_cancel">取消</a >',
	                            '</div>',
		                	'</div>',
		                    '<div>',
		                        '<a href="javascript:;" class="add-link add_offline_box"><i></i>新增上课地点</a>',
		                    '</div>',
		                '</div>',
		            '</div>',
		        '</div>',
		    '</div>',
		    '<a href="javascript:;" class="s_select close_box"></a>',
            '</div>'
		].join("");
		break;
	case "outsite_link" :
		var html = [
            '<div class="s_videoCon outsite_link_box" style="display:none">',
            '<div class="s_inner">',
            '<div class="s_i_hd">',
            '<div class="s_i_hd_notice clearfix">',
            '<div class="fl"><img alt="" src="http://res.ckimg.com/sites/www/v2/images/public/ico_warning_16x16.png"></div>',
            '<div class="fl">',
			'<span>请确保你对所添加链接拥有完全的版权</span>',
			'</div></div></div><div class="s_i_bd clearfix">',
			'<form class="s_i_form clearfix" action="">',
			'<div class="formItem">',
			'<label class="form_label" for="">',
			'<i>*</i><span>视频链接：</span>',
			'</label><div class="form_field">',
			'<input type="text" style="width:620px;" class="form_text videosrc">',
			'</div></div></form></div></div>',
			'<a class="s_select close_box" href="javascript:;"></a></div>'
		].join("");
		break;
	}
	
	$selector.after(html);
	$selector.next("div.s_videoCon").slideDown("fast");
	if (!($.browser.msie && $.browser.version == '6.0' && type == "live_class")) {
		if (type != 'offline_class') {
			$selector.next("div.s_videoCon").find("select").divSelect('260');
		}
	}
	
	if (type == 'offline_class') {
		ajaxOfflineAddress(0);
	}
}

//个性化学习-添加课件 S
var selectCoureswareClass = function($selector, type){
	
	switch(type){
	case "video_class" :
		if($("#ps_video_box").is(":hidden")) {
			$("#ps_video_box").show();
		} else {
			var html = [
	            '<div class="s_videoCon video_class_box mb20" id="ps_video_box" style="display:none">',
	            '<div class="s_inner">',
	            '<div class="s_i_hd">',	
	            '<a class="n_btn34lg_add mr15 pickVideos" href="javascript:;"><span>从视频库中选择</span></a>',
	            '<span class="s_i_hd_tips">未上传的视频请先上传至视频库 <a class="c_0065cb" href="/?mod=video&act=upload&do=show'+authorizeUri+'" target="_blank">上传视频</a></span>',
	            '</div><div class="tc mt30">请为该视频课添加视频文件</div></div>',
	            '<a class="s_select close_box" href="javascript:;"></a></div>'
	        ].join("");
			$selector.after(html);
			$selector.next("div.s_videoCon").slideDown("fast");
		}
		break;
	case "courseware_class" : 
		if($("#ps_courseware_box").is(":hidden")){
			$("#ps_courseware_box").show();
		} else {
			var courseware_url = '';
            if(IsAuthorize) {
                courseware_url = '?mod=teacher&amp;act=courseware&amp;do=iupload&amp;authorize='+IsAuthorize+'&amp;sid='+SID;
            } else {
                courseware_url = '?mod=seller&amp;act=courseware&amp;do=iupload';
            }
			var html = [
	            '<div class="s_videoCon attach_class_box" id="ps_courseware_box" style="display:none">',
	            '<div class="s_inner">',
	            '<div class="s_i_hd">',	
	            '<a class="n_btn34lg_add mr15 pickCoureswares" href="javascript:;"><span>从课件库中选择</span></a>',
	            '<span class="s_i_hd_tips">未上传的课件请先上传至课件库 <a class="c_0065cb" href="'+courseware_url+'" target="_blank">上传课件</a></span>',
	            '</div><div class="s_i_hd" id="selectedCourseware"></div></div>',
	            '<a class="s_select close_box" href="javascript:;"></a></div>'
	        ].join("");
			$selector.after(html);
			$selector.next("div.s_videoCon").slideDown("fast");
		}
		break;
	}
	
	if ( !($.browser.msie && $.browser.version == '6.0' && type == "live_class") ){
		$selector.next("div.s_videoCon").find("select").divSelect('260');
	}
}

var updateSelectedPSVideoCount = function(Coureswares, dialogBox) {
	var cocnt = 0;
	for (var key in Coureswares) {
		if (Coureswares[key] != null) {
			if (Coureswares[key].vid > 0) {
				cocnt = cocnt + 1;
			}
		}
	}
	dialogBox.find("div.co_select_no>em").text(cocnt);
}
//个性化学习视频添加弹窗
var pickPSVideos = function(url, callback, Coureswares, unit) {
	var pickVideoBox = $.ckAjaxBoxy({
		url : url+"&random="+Math.random(),
		title : "从视频库中选择",
		width : 674,
		height : 526,
		callback : function() {
			var dialogBox = $("#fe_dialogBox");
			updateSelectedPSVideoCount(Coureswares[unit], dialogBox);
			dialogBox.inputTips();
			var videoCon = $("#fe_dialogBox div.co_video_list");
			$.each(videoCon.find("div.video_item"), function(i, n) {
				for (var h = 0; h < Coureswares[unit].length; h++) {
					if (Coureswares[unit][h].vid == $(n).attr('vid')) {
						$(n).addClass("co_video_con_select");
					}
				}
			});
			videoCon.find("li>div.video_item").unbind().hover(
				function() {
					$(this).addClass('co_video_con_hover');
				},
				function() {
					$(this).removeClass('co_video_con_hover');
				}
			).bind('click', function() {
				if ($(this).hasClass('co_video_con_select')) {
					for (var i = 0; i < Coureswares[unit].length; i++) {
						if ($(this).attr('vid') == Coureswares[unit][i].vid) {
							Coureswares[unit].splice(i, 1);
						}
					}
					$(this).removeClass('co_video_con_select');
				} else {
					if (isUniqueCourseware($(this).attr('vid'), psstudyType.video)) {
						alert("不能重复添加视频课件，其它学习单元已经占用此视频课件!");
						return false;
					}
					$(this).addClass('co_video_con_select');
					var video = { 'vid' : 0, 'thumb' : '', 'name' : '', 'type' : '', 'ico' : '', 'aid' : 0, 'cn' : ''};
						video.vid   = $(this).attr('vid');
						video.thumb = $(this).find("img").attr('src');
						video.name  = $(this).find('p').text();
						video.type  = psstudyType.video;
						video.ico   = '';
						video.aid   = 0;
						video.cn    = '';
					Coureswares[unit].push(video);
				}
				updateSelectedPSVideoCount(Coureswares[unit], dialogBox);
			});
			dialogBox.find("#popSelVideoClass").unbind().bind('change',function() {
				pickPSVideos("/?mod=video&act=list&do=popSelect"+authorizeUri+"&sid="+SID+"&classid="+$(this).val(), callback, Coureswares, unit);
			});
			dialogBox.find("input.co_select_btn").unbind().bind('click', function() {
				pickPSVideos("/?mod=video&act=list&do=popSelect"+authorizeUri+"&sid="+SID+"&keyword="+encodeURIComponent(dialogBox.find("input.form_text").val()), callback, Coureswares, unit);
			});
			dialogBox.find("a.goback").unbind().bind('click', function() {
				pickPSVideos("/?mod=video&act=list&do=popSelect"+authorizeUri+"&sid="+SID+"&keyword=");
				return false;
			});
			$("#fe_dialogBox a.ajaxLink").unbind().bind('click', function() {
				pickPSVideos($(this).attr('href')+authorizeUri, callback, Coureswares, unit);
				return false;
			});
			dialogBox.find("a.cancel").unbind().bind('click', function() {
				pickVideoBox.cancel();
			});
			dialogBox.find('a.submit').unbind().bind('click', function() {
				pickVideoBox.cancel();
				callback();
			});
		}
	});
}
//个性化学习-添加课件 E
var pickTeacher = function(url, callback, teacher){
	var pickTeacherBox = $.ckAjaxBoxy({
		url : url,
		title : "选择老师",
		width : 658,
		height : 508,
		callback : function(){
			var teacherCon = $("#fe_dialogBox div.t_teacher_con");
			$.each(teacherCon, function(i, n){
				if(teacher.uid != 0 && $(teacherCon[i]).attr('uid') == teacher.uid){
					$(teacherCon[i]).addClass('t_teacher_con_select');
				}
			});
			teacherCon.unbind().hover(
				function(){
					$(this).addClass('t_teacher_con_hover');
				},
				function(){
					$(this).removeClass('t_teacher_con_hover');
				}
			).bind('click', function(){
				if($(this).hasClass('t_teacher_con_select')){
					$(this).removeClass('t_teacher_con_select');
				}else{
					$(this).addClass('t_teacher_con_select');
					teacher.uid = $(this).attr('uid');
					teacher.name = $(this).attr('nickname');
					teacher.pic = $(this).find('img').attr('src');
					pickTeacherBox.cancel();
					callback(teacher);
				}
			});
			$("#fe_dialogBox a.ajaxLink").unbind().bind('click', function(){
				pickTeacher($(this).attr('href')+authorizeUri, callback, teacher);
				return false;
			})
		}
	});
}

var pickVideos = function(url, callback, videos){
	var pickVideoBox = $.ckAjaxBoxy({
		url : url+"&random="+Math.random(),
		title : "从视频库中选择",
		width : 674,
		height : 526,
		callback : function(){
			var dialogBox = $("#fe_dialogBox");
			dialogBox.find("div.co_select_no>em").text(videos.length);
			dialogBox.inputTips();
			var videoCon = $("#fe_dialogBox div.co_video_list");
			$.each(videoCon.find("div.video_item"), function(i, n){
				for(var h=0; h<videos.length; h++){
					if(videos[h].vid == $(n).attr('vid')){
						$(n).addClass("co_video_con_select");
					}
				}
			});
			videoCon.find("li>div.video_item").unbind().hover(
				function(){
					$(this).addClass('co_video_con_hover');
				},
				function(){
					$(this).removeClass('co_video_con_hover');
				}
			).bind('click', function(){
				if($(this).hasClass('co_video_con_select')){
					for(var i=0; i<videos.length; i++){
						if($(this).attr('vid') == videos[i].vid){
							videos.splice(i, 1);
						}
					}
					$(this).removeClass('co_video_con_select');
				}else{
					$(this).addClass('co_video_con_select');
					var video = {'vid':0, 'thumb':'', 'name':''}
					video.vid = $(this).attr('vid');
					video.thumb = $(this).find("img").attr('src');
					video.name = $(this).find('p').text();
					videos.push(video);
				}
				dialogBox.find("div.co_select_no>em").text(videos.length);
			});
			dialogBox.find("#popSelVideoClass").unbind().bind('change',function(){
				pickVideos("/?mod=video&act=list&do=popSelect"+authorizeUri+"&sid="+SID+"&classid="+$(this).val(), callback, videos);
			});
			dialogBox.find("input.co_select_btn").unbind().bind('click', function(){
				pickVideos("/?mod=video&act=list&do=popSelect"+authorizeUri+"&sid="+SID+"&keyword="+encodeURIComponent(dialogBox.find("input.form_text").val()), callback, videos);
			});
			dialogBox.find("a.goback").unbind().bind('click', function(){
				pickVideos("/?mod=video&act=list&do=popSelect"+authorizeUri+"&sid="+SID+"&keyword=");
				return false;
			});
			$("#fe_dialogBox a.ajaxLink").unbind().bind('click', function(){
				pickVideos($(this).attr('href')+authorizeUri, callback, videos);
				return false;
			});
			dialogBox.find("a.cancel").unbind().bind('click', function(){
				pickVideoBox.cancel();
			});
			dialogBox.find('a.submit').unbind().bind('click', function(){
				pickVideoBox.cancel();
				callback();
			});
		}
	});
}

//个性化学习-关联知识点 S
var add_knowledge = function(url) {
	var knowledgeBox = $.ckAjaxBoxy({
		url      : url,
		title    : '('+CateRoute+')'+" 全部知识点:",
		width    : 540,
		height   : 424,
		callback : function() {
			var select_kl_id = $('#select_kl_id').val();
			if (select_kl_id > 0) {
				$('#knowledge_radio input').each(function(item) {
					if ($(this).val() == select_kl_id) {
						$(this).attr("checked", "checked");
						var mainID = $(this).parent().parent().parent().parent().attr('data-main');
						if (mainID > 0) {
							$('#data_main_' + mainID).parent().find('ul').addClass('state-show');
							$('#data_main_' + mainID).parent().find('i').addClass('state-zk');
						}
					}
				});
			}
			
			$("#cancel").click(function() {
				knowledgeBox.cancel();
			});
			
			$("#fe_dialogBox a.ajaxLink").unbind("click").bind('click', function() {
				add_knowledge($(this).attr('href')+authorizeUri);
				return false;
			});
			
			$("#submit").click(function() {
				if ($('input[name=knowledge]').is(':checked')) {
					var klid   = $('input[name=knowledge]:checked').val();
					var divid  = '#kl_' + klid;
					var kltext = $(divid).text();
					$('#select_kl_id').val(klid);
					$('#select_kl_text').text(kltext);
					knowledgeBox.cancel();
					return true;
				} else {
					$.ckTipsBoxy({message:"请选择一个和课程相对应的知识点", type:"error", mask:true});
					return false;
				}
			});
		}
	});
}

//个性化学习-关联知识点 E
var getUnitSequence = function() {
	var cellItemWrap = $('#ps_unit_box').find('.cell-item-wrap');
	return cellItemWrap.length;
}

var addUnitTemplate = function(SeqID) {
	var num  = SeqID + 1;
	var html = [
	        '<div class="cell-item-wrap mb20">',
	        '<div class="mb10">学习单元' + num + '</div>',
	        '<ul class="items-list clearfix" unit="'+ num +'">',
	        '<li class="type-3 selectVideos" unit="'+ num +'"><div class="inner"><i></i>添加视频</div></li>',
	        '<li class="type-3 selectCoureswares"  unit="'+ num +'"><div class="inner"><i></i>添加课件</div></li>',
	        '</ul><div class="c_999 mb20">你可以通过拖拽改变个性化学习先后顺序。</div></div>',
	    ].join("");
	$('#ps_unit_box').append(html);
}

$(function() {
	
	$("#CourseDanceBox").dance({
		click : {
			//个性化学习Q3-添加单元打包
			"a.ps_unit_box_add" : function() {
				//检查单元序列
				var SeqID = getUnitSequence();
				if (SeqID < 3) {
					//生成单元模板
					addUnitTemplate(SeqID);
					$("html, body").animate({scrollTop: $("#ps_unit_box").children().last().offset().top}, 1000);
				} else {
					if (!$(this).hasClass('disabled')) {
						$(this).addClass('disabled');
						$.ckAlert({message:"每节只允许添加三个学习单元"});
					}
				}
			},
			"a.cell-item-del" : function() {
				$(this).parent("li").remove();
			},
			//个性化学习Q3-添加单元打包
			"a.i_e_down" : function(){
				var cid = $(this).parent("div.itemRow").attr("cid");
				$("#section_"+cid).slideDown('fast');
				$(this).removeClass("i_e_down").addClass("i_e_up");
			},
			"a.i_e_up" : function(){
				var cid = $(this).parent("div.itemRow").attr("cid");
				$("#section_"+cid).slideUp('fast');
				$(this).removeClass("i_e_up").addClass("i_e_down");
			},
			"a.add_section" : function(){
				if($("#CourseDanceBox").find("textarea").length >= 1){
					$.ckAlert({message:"您有编辑状态的课程未操作完成，请保存或取消后再操作"});
					return false;
				}
				var $obj = $(this).parent().parent(".item_add");
				if ($obj.attr('disable') == 'disable') {
					return;
				}
				//个性化学习资料数据初始化
				if (Individuation == 1) {
					Coureswares    = [];
					Coureswares[1] = [];
					Coureswares[2] = [];
					Coureswares[3] = [];
				}
				$obj.attr('disable', 'disable');
				$obj.fadeOut("fast", function(){
					addSection($obj);
					$obj.attr('disable', '');
				});
			},
			"a.n_btn34gr_b" : function(){
				var $subBox = $(this).parent().parent().parent("div.subBox");
				$subBox.slideUp("fast", function(){
					$subBox.prev("div.item").fadeOut("fast", function(){
						if($subBox.hasClass("editContentBox")){
							var $itemRow = $subBox.next("div.itemRow");
							$itemRow.fadeIn("fast");
							if($itemRow.find("a.i_e_up").length > 0){
								$("#section_"+$itemRow.attr('cid')).slideDown("fast");
							}
						}else{
							$subBox.next("div.item_add").fadeIn("fast");
						}
						var $partBox = $subBox.parent("div.sedu_tBox");
						$(this).remove();
						$subBox.remove();
						resetSectionNu($partBox);
					});
				});
			},
			"a.select_class" : function(){
				var $selector = $(this).parent("div"),
					class_type = $(this).attr("type");
				$selector.slideUp("fast", function(){
					selectClass($selector, class_type);
					var $add_box = $selector.next("div.s_videoCon");
					$add_box.find("a.close_box").bind("click", function(){
						$add_box.slideUp("fast", function(){
							$add_box.remove();
							$selector.slideDown("fast");
						});
					});
				});
			},
			//个性化学习-添加课件 S
			"a.select_couresware_class" : function(){
				var $selector = $(this).parent("div"),
					class_type = $(this).attr("type");
				
				if(class_type == 'video_class') {
					$selector.slideUp("fast", function(){
						selectCoureswareClass($selector, class_type);
						var $add_box1 = $selector.next("div.s_videoCon");
						$add_box1.find("a.close_box").bind("click", function(){
							$add_box1.slideUp("fast", function(){
//								$add_box1.remove();
								$selector.slideDown("fast");
							});
						});
					});
				} else if(class_type == 'courseware_class') {
					$selector.slideUp("fast", function(){
						selectCoureswareClass($selector, class_type);
						var $add_box2 = $selector.next("div.s_videoCon");
						$add_box2.find("a.close_box").bind("click", function(){
							$add_box2.slideUp("fast", function(){
//								$add_box2.remove();
								$selector.slideDown("fast");
							});
						});
					});
				}
			},
			//选择个性化视频
			".selectVideos" : function() {
				var unit              = $(this).attr('unit'),	//当前操作的单元
					$pick_box         = $(this).parent('.items-list'),
					$ul_box           = $pick_box.parent(),
					$addedVideoList   = $(this).parent('.items-list').find(".filtrate");
					Coureswares[unit] = [];
					
				if ($addedVideoList.length > 0) {
					$.each($addedVideoList, function(idx, item) {
						var video       = { 'vid' : 0, 'thumb' : '', 'name' : '', 'type' : '', 'ico' : '', 'aid' : 0, 'cn' : ''};
							video.vid   = $(item).attr('vid');
							video.aid   = $(item).attr('aid');
							video.name  = $(item).find('.right-part').text();
							video.thumb = $(item).find('img').attr('src');
							video.type  = $(item).attr('type');
							video.ico   = $(item).attr('ico');
							video.cn    = $(item).attr('cn');;
						Coureswares[unit].push(video);
					});
				}
				pickPSVideos("/?mod=video&act=list&do=popSelect" + authorizeUri + "&sid=" + SID + "&random=" + Math.random(), function() {
					var html = buildCoursewareListNode(unit, Coureswares);
					$pick_box.replaceWith(html);
					$ul_box.find('ul').dragsort({
						dragSelector: ".filtrate", 
						dragBetween: false, 
						dragEnd: function() {}, 
						placeHolderTemplate: "<li></li>",
						scrollSpeed: 5
					});
				}, Coureswares, unit);
			},
			//选择个性化资料
			".selectCoureswares" : function() {
				var unit              = $(this).attr('unit'),	//当前操作的单元
					$pick_box         = $(this).parent('.items-list'),
					$ul_box           = $pick_box.parent(),
					$addedAttachList  = $(this).parent('.items-list').find(".filtrate");
					Coureswares[unit] = [];
				
				if ($addedAttachList.length > 0) {
					$.each($addedAttachList, function(idx, item) {
						var attach   = { 'vid' : 0, 'thumb' : '', 'name' : '', 'type' : '', 'ico' : '', 'aid' : 0, 'cn' : ''};
							attach.vid   = $(item).attr('vid');
							attach.aid   = $(item).attr('aid');
							attach.name  = $(item).find('.right-part').text();
							attach.thumb = $(item).find('img').attr('src');
							attach.type  = $(item).attr('type');
							attach.ico   = $(item).attr('ico');
							attach.cn    = $(item).attr('cn');
						Coureswares[unit].push(attach);
					});
				}
				pickPSCoursewares("/?mod=course&act=courseware&do=select" + authorizeUri + "&courseid=" + CourseID + "&random=" + Math.random(), function() {
					var html = buildCoursewareListNode(unit, Coureswares);
					$pick_box.replaceWith(html);
					$ul_box.find('ul').dragsort({
						dragSelector: ".filtrate", 
						dragBetween: false, 
						dragEnd: function() {}, 
						placeHolderTemplate: "<li></li>",
						scrollSpeed: 5
					});
				}, Coureswares, unit);
			},
			"a.pickCoureswares" : function(){
				var attachs = [],
				$pick_box = $(this).parent("div.s_i_hd"),
				$addedAttachList = $(this).parent().next("#selectedCourseware").find("li");
				if($addedAttachList.length > 0){
					$.each($addedAttachList, function(idx, item){
						var attach = {'aid':0}
						attach.aid = $(item).attr('aid');
						attachs.push(attach);
					});
				}
				selectCourseware("/?mod=course&act=courseware&do=select"+authorizeUri+"&courseid="+CourseID+"&tm="+new Date().getTime(),attachs);
			},
			//个性化学习-添加课件 E
			"a.pickTeacher" : function(){
				var $pick_link = $(this);
				if($pick_link.text() == "更换老师"){
					var teacher_img = $pick_link.prev("img"),
						teacher = {'uid':teacher_img.attr('uid'), 'pic':teacher_img.attr('src'), 'name':teacher_img.attr('title')};
				}else{
					var teacher = {'uid':0, 'pic':'', 'name':''};
				}
				pickTeacher("/?mod=course&act=create&do=pickTeacher"+authorizeUri+"&sid="+SID+"&random="+Math.random(), function(){
					if($pick_link.prev('img').length > 0){
						$pick_link.prev('img').replaceWith('<img width="60" height="60" title="'+teacher.name+'" uid="'+teacher.uid+'" src="'+teacher.pic+'" class="s_i_picTeacher" /> ');
					}else{
						$pick_link.before('<img width="60" height="60" title="'+teacher.name+'" uid="'+teacher.uid+'" src="'+teacher.pic+'" class="s_i_picTeacher" /> ').text("更换老师");
					}		
				}, teacher);
			},
			"a.submit_section" : function() {
				var $add_box = $(this).parent().parent().parent("div.subBox"),
					$add_item = $add_box.prev("div.item");
				if ($add_item.hasClass("editTitleBox")) {
					saveSection($add_box, $add_item, sectionOpCode.edit);
				} else {
					saveSection($add_box, $add_item, sectionOpCode.add);
				}
				return;
			},
			"a.submit_is_section" : function() {
				var $add_box = $(this).parent().parent().parent("div.subBox"),
					$add_item = $add_box.prev("div.item");
				if ($add_item.hasClass("editTitleBox")) {
					saveISSection($add_box, $add_item, sectionOpCode.edit);
				} else {
					saveISSection($add_box, $add_item, sectionOpCode.add);
				}
				return;
			},
			"a.pickVideos" : function(){
				var videos = [],
					$pick_box = $(this).parent("div.s_i_hd"),
					$addedVideoList = $(this).parent().next("div.s_i_bd").find("li");
				if($addedVideoList.length > 0){
					$.each($addedVideoList, function(idx, item){
						var video = {'vid':0, 'thumb':'', 'name':''}
						video.vid = $(item).attr('vid');
						video.name = $(item).find('p').text();
						video.thumb = $(item).find('img').attr('src');
						videos.push(video);
					});
				}
				pickVideos("/?mod=video&act=list&do=popSelect"+authorizeUri+"&sid="+SID+"&random="+Math.random(), function(){
					var html = buildVideoListNode(videos);
					$videoListBox = $pick_box.next("div.s_i_bd");
					if($videoListBox.length > 0){
						$videoListBox.replaceWith(html);
					}else{
						$pick_box.next("div.tc").remove();
						$pick_box.after(html);
					}
					$videoListBox = $pick_box.next("div.s_i_bd");
					$videoListBox.find('ul').dragsort({
						dragSelector: "div", 
						dragBetween: false, 
						dragEnd: function() {}, 
						placeHolderTemplate: "<li><div class='s_i_picBox'></div></li>",
						scrollSpeed: 5
					});
					
					$videoListBox.find("a.s_i_close").unbind().bind('click', function(){
						$(this).parent().parent("li").remove();
						if($videoListBox.find("li").length == 0){
							$("#video_save_tip").hide();
							$videoListBox.replaceWith('<div class="tc mt30">请为该视频课添加视频文件</div>');
						}
					});
					
					if (videos.length > 0 && SaveDisplay == 'block') {
						$("#video_save_tip").show();
					}
				}, videos);
			},
			"div.itemRow a.c_edit" : function() {
				if($("#CourseDanceBox").find("textarea").length >= 1) {
					$.ckAlert({message:"您有编辑状态的课程未操作完成，请保存或取消后再操作"});
					return false;
				}
				var $add_item  = $(this).parent().parent().parent("div.itemRow"),
					$add_box   = $("#section_"+$add_item.attr('cid')),
					class_info = getClassInfoFromNode($add_item, $add_box),
					edit_html  = editSection(class_info);
				
				if(checkCurrClassEdit($add_item.attr('cid'), sectionOpCode.edit) !== true) {
					return false;
				}
				
				if ($add_item.attr('disable') == 'disable') {
					return;
				}
				$add_item.attr('disable', 'disable');
				
				$add_box.slideUp("fast", function() {
					$add_item.fadeOut("fast", function() {
						$add_item.attr('disable', '');
						$add_item.before(edit_html);
						//个性化设置
						if(Individuation == 1) {
							addCoursewareHandler();
							$AttachListBox = $('#ps_unit_box');
//							$AttachListBox.find('ul').dragsort({
//								dragSelector : "div.s_c_oCourseBox", 
//								dragBetween  : false, 
//								dragEnd      : function() {},
//								scrollSpeed  : 5,
//								placeHolderTemplate: "<li></li>"
//							});
							$AttachListBox.find('ul').dragsort({
								dragSelector: ".filtrate", 
								dragBetween: false, 
								dragEnd: function() {}, 
								placeHolderTemplate: "<li></li>",
								scrollSpeed: 5
							});
						}
						$add_item.prev().prev("div.editTitleBox").fadeIn("fast", function() {
							var $editContentBox = $add_item.prev("div.editContentBox");
							if (class_info.study_type == studyType.curr || class_info.study_type == studyType.live){
								if (!($.browser.msie && $.browser.version == '6.0'))
									$editContentBox.find("select").divSelect('260');
							} else if(class_info.study_type == studyType.video) {
								if (class_info.video_type == "video") {
									$videoListBox = $editContentBox.find("div.s_i_bd");
									$videoListBox.find('ul').dragsort({
										dragSelector: "div", 
										dragBetween: false, 
										dragEnd: function() {}, 
										placeHolderTemplate: "<li><div class='s_i_picBox'></div></li>",
										scrollSpeed: 5
									});
									
									$videoListBox.find("a.s_i_close").unbind().bind('click', function(){
										$(this).parent().parent("li").remove();
										if($videoListBox.find("li").length == 0){
											$videoListBox.replaceWith('<div class="tc mt30">请为该视频课添加视频文件</div>');
										}
									});
								}
							} else if(class_info.study_type == studyType.offline) {
								ajaxOfflineAddress(class_info);
							}
							$add_item.prev("div.editContentBox").slideDown("fast");
						});
					});
				});
			},
			"div.itemRow a.c_del" : function(){
				var $add_item = $(this).parent().parent().parent("div.itemRow"),
					$add_box = $("#section_"+$add_item.attr('cid')),
					class_info = getClassInfoFromNode($add_item, $add_box);
				if(checkCurrClassEdit($add_item.attr('cid'), sectionOpCode.del) !== true){
					return false;
				}
				$.ckConfirm({
					message : "你确定要删除该节？",
					ok : function(){
						if(Individuation == 1) {
							saveISSection($add_box, $add_item, sectionOpCode.del);
						} else {
							saveSection($add_box, $add_item, sectionOpCode.del);
						}
					}
				});
			},
			"div.itemRow a.c_add" : function(){
				$insert_box = $(this).next("div.h_add_m");
				if($insert_box.length > 0){
					$insert_box.remove();
				}else{
					var html = [
			            '<div style="display:block;" class="h_add_m">',
						'<a href="javascript:;" class="insert_before">向上插入1讲</a>',
						'<a href="javascript:;" class="insert_after">向下插入1讲</a>',
						'<i class="arrow"></i>',
						'</div>'
		            ].join("");
					$(this).after(html);
				}
			},
			"a.edit_part" : function(){
				var $add_box = $(this).parent().parent().parent("div.sedu_t");
				if ($add_box.attr('disable') == 'disable') {
					return;
				}
				$add_box.attr('disable', 'disable');
				$add_box.fadeOut("fast", function() {
					addPart($add_box, partOpCode.edit);
					$add_box.attr('disable', '');
				});
			},
			"a.add_part" : function(){
				var $obj = $(this).parent("div.sedu_t_add");
				if ($obj.attr('disable') == 'disable') {
					return;
				}
				$obj.attr('disable', 'disable');
				$obj.fadeOut("fast", function(){
					addPart($obj, partOpCode.add);
					$obj.attr('disable', '');
				});
			},
			"a.add_part_cancel" : function(){
				var $obj = $(this).parent().parent("div.sedu_t_edit");
				$obj.fadeOut("fast", function(){
					if ($obj.hasClass("edit_part_type")){
						$obj.next("div.sedu_t").fadeIn("fast");
					}else{
						$obj.next("div.sedu_t_add").fadeIn("fast");
					}
					$obj.remove();
				})
			},
			"a.add_part_submit" : function(){
				var $add_box = $(this).parent().parent("div.sedu_t_edit");
				if ($add_box.hasClass("edit_part_type")){
					savePart($add_box, partOpCode.edit);
				}else{
					savePart($add_box, partOpCode.add);
				}
			},
			"a.del_part" : function(){
				var $add_box = $(this).parent().parent().parent("div.sedu_t");
				$.ckConfirm({
					message : "您确定要删除该章节吗？",
					ok : function(){
						savePart($add_box, partOpCode.del);
					}
				});
			},
			"a.insert_before" : function(){
				if($("#CourseDanceBox").find("textarea").length >= 1){
					$.ckAlert({message:"您有编辑状态的课程未操作完成，请保存或取消后再操作"});
					return false;
				}
				var $add_item = $(this).parent().parent().parent().parent("div.itemRow");
				addSection($add_item, "insert_before");
			},
			"a.insert_after" : function(){
				if($("#CourseDanceBox").find("textarea").length >= 1){
					$.ckAlert({message:"您有编辑状态的课程未操作完成，请保存或取消后再操作"});
					return false;
				}
				var $add_item = $(this).parent().parent().parent().parent("div.itemRow");
				addSection($add_item, "insert_after");
			},
			"a.move_u" : function(){
				var $base_item = $(this).parent().parent("div.itemRow"),
					$to_item = $base_item.prev().prev("div.itemRow");
				if($to_item.length <= 0){
					return false;
				}else{
					if($to_item.css("display") == "none"){
						$.ckTipsBoxy({
							message : "移动前，请先退出编辑状态",
							width : 250,
							type : "notice",
							mask : true
						});
						return false;
					}
				}
				moveSection($base_item, $to_item, "up");
			},
			"a.move_d" : function(){
				var $base_item = $(this).parent().parent("div.itemRow"),
				$to_item = $base_item.next().next("div.item");
				if($to_item.length <= 0){
					return false;
				}else{
					if($to_item.hasClass("editTitleBox")){
						$.ckTipsBoxy({
							message : "移动前，请先退出编辑状态",
							width : 250,
							type : "notice",
							mask : true
						});
						return false;
					}
				}
				moveSection($base_item, $to_item, "down");
			},
			"a.add_offline_box" : function() {
				if ($(this).parent().prev().css('display') == 'none') {
					$("#idProvince option:first").prop('selected', 'selected');
					$('#idCity').empty();
				    $('#idCity').append('<option value="0">市区</option>');
					editoffline = 0;
					$(this).parent().prev().find('.offline_address').val('');
					$(this).parent().prev().find('.offline_address_tips').show();
					$(this).parent().prev().show();
				}
			},
			"a.offline_address_cancel" : function() {
				$('.add-box').hide();
			},
			"a.offline_address_submit" : function() {
				var offlineid = $("#offlineid").val();
				var province  = $("#idProvince").val();
				var city      = $("#idCity").val();
				var idProvince= $("#idProvince").find("option:selected").text();;
				var idCity    = $("#idCity").find("option:selected").text();;
				var address   = $(".offline_address").val();
				
				if (checkCity(province, city) == false) {
					$.ckAlert({message : '请选择所在城市！'});
					return;
				}

				if (checkAddress(address) == false) {
					$.ckAlert({message : '请填写详细地址！'});
					return;
				}
				
				if (editoffline > 0) {
					offlineid = editoffline;
				}
				
				var params  = [
			        "&city="      + city,
			        "&idProvince="+ encodeURIComponent(idProvince),
			        "&idCity="    + encodeURIComponent(idCity),
			        "&address="   + encodeURIComponent(address),
			        "&authorize=" + encodeURIComponent(IsAuthorize),
			        "&isteacher=" + encodeURIComponent(IsTeacher),
			        "&courseid="  + encodeURIComponent(CourseID),
			        "&sid="       + encodeURIComponent(SID),
			        "&offlineid=" + encodeURIComponent(offlineid),
			        "&authorize=" + encodeURIComponent(IsAuthorize),
			 	].join('');
				
				$.ajax({
					url        : "/?mod=course&act=offline&do=save&tm="+new Date().getTime(),
					type       : "post",
					data       : params+"&_t="+_t,
					dataType   : "json",
					async      : false,
					beforeSend : function() {
						tipboxy = $.ckTipsBoxy({type:"loading", message : "数据提交中...", mask : true});
					},
					success : function(ret) {
						tipboxy.cancel();
						if (ret.code == 0) {
							var c = getLocation(city);
							if (editoffline) {
								$('#offline_'+editoffline+' i').text(c.c + c.a);
								$('#offline_'+editoffline+' span').text(ret.data.Address);
							} else {
								var li = '<li class="clearfix" offlineid='+ ret.data.OffLineID +' city='+ city +'><div class="addr"><label id="offline_'+ret.data.OffLineID+'"><input type="checkbox" checked="checked" value="' + ret.data.OffLineID +'"><i>' + c.c + c.a +'</i><span>' + ret.data.Address + '</span></label></div>';
								    li += '<div class="addr-edit"><a class="edit" href="javascript:;">编辑</a><span>|</span><a href="javascript:;" class="del">删除</a></div></li>';
								    li += '</li>';
								$('.addr-list').prepend(li);
							}
							$('.add-box').hide();
						} else {
							$.ckAlert({message : ret.result});
						}
					}
				});
				editoffline = 0;
			},
          	".addr-list .addr-edit a.edit" : function() {
          		var offlineid = $(this).parent().parent().attr('offlineid');
          		var city      = $(this).parent().parent().attr('city');
          		var address   = $(this).parent().parent().find('.addr span').text();
          		editoffline   = offlineid;
          		initLocation(city);
          		$('.add-box .offline_address_tips').hide();
          		$('.add-box .offline_address').val(address);
          		$('.add-box').show();
			},
            ".addr-list .addr-edit a.del" : function() {
            	var offlineobj = $(this).parent().parent();
            	var offlineid  = $(this).parent().parent().attr('offlineid');
            	var state = false;
            	$.each(delOfflines, function(i, item){
            		if (item == offlineid) {
            			state = true;
            			$.ckAlert({message : '上课地址正在使用中不能删除！'});
            			return;
            		}
            	});
            	if (state) {
        			return;
            	}
            	$.ckConfirm({
					message : "您确定要删除该地址吗？",
					ok : function() {
						$.ajax({
							url:"/?mod=course&act=offline&do=del&authorize="+IsAuthorize+"&sid="+SID+"&offlineid="+offlineid+"&tm="+new Date().getTime(),
							type:'get',
							data : "&sid="+SID+"&_t="+_t,
							dataType:'json',
							success:function(ret) {
								if (ret.code == 0) {
									offlineobj.remove();
								}
								$.ckAlert({message : ret.data});
							}
						});
						$(this).parent().parent().remove();
					}
				});
			},
			//个性化学习-关联知识点 S
			"a.add_knowledge" : function() {
				$.ajax({
					url:"/?mod=course&act=knowledge&do=relevance&gid="+GID+"&tm="+new Date().getTime(),
					type:'get',
					dataType:'html',
					success:function(ret){
						add_knowledge("/?mod=course&act=knowledge&do=relevance&gid="+GID+"&tm="+new Date().getTime());
					}
				});
			}
			//个性化学习-关联知识点 E
		},
		focus : {
			".offline_address" : function() {
				if ($(this).val() == '') {
					$('.offline_address_tips').hide();
				}
			}
		},
		blur : {
			".offline_address" : function() {
				if ($(this).val() == '') {
					$('.offline_address_tips').show();
				}
			}
		},
		mouseover : {
			"div.itemRow" : function(){
				$(this).addClass("item_hover");
				$(this).find('.i_extra').hide();
			},
			"div.h_add_m" : function(){
				$(this).parent().parent().parent("div.itemRow").addClass("item_hover");
			},
			".liveZBiHelp" : function() {
				$('.p-live-tips-wrap').show();
			}
		},
		mouseout : {
			"div.itemRow" : function(){
				$(this).find('.i_extra').show();
				var $itemRow = $(this);
				$itemRow.removeClass("item_hover");
				setTimeout(function(){
					if(!$itemRow.hasClass("item_hover")){
						$itemRow.find('div.h_add_m').remove();
					}
				}, 100);
			},
			"div.h_add_m" : function(){
				var $obj = $(this);
				setTimeout(function(){
					if(!$obj.parent().parent().parent("div.itemRow").hasClass("item_hover")){
						$obj.remove();
					}
				},100);
			},
			".liveZBiHelp" : function() {
				$('.p-live-tips-wrap').hide();
			}
		}
	});
})